Part 6: Django CRUD, Update

Continued from Part 5: Django CRUD, Delete

Full code onĀ https://github.com/shanegibney/djangoCRUD

We may wish to update the model ‘Members’. Let us start by adding an edit icon to the table in ‘index.html’.

<td><a href="{% url 'edit_new' item.id %}"><span class="glyphicon glyphicon-pencil"></span></a></td>

If you are not using Bootstrap replace the span tags with ‘edit’.

<td><a href="{% url 'edit_new' item.id %}">edit</a></td>

This will bring us to a url named ‘edit_new’ and also will pass the ‘id’. Create this url in urls.py,

url(r'^edit/(?P\d+)/$', home.edit_new, name='edit_new'),

Django then brings us to the view ‘edit_new’ which we will now create in ‘views.py’,

def edit_new(request, id):
    post = get_object_or_404(Members, pk=id)
    if request.method == "POST":
        form = MemberForm(request.POST, instance=post)
        if form.is_valid():
            post = form.save(commit=False) 
            post.save()
            return redirect('init')
    else:
        form = MemberForm(instance=post)
    return render(request, 'member_edit.html', {'form': form})

This is almost identical to the view ‘member_new’ which we used to create a new instance of the model ‘Members’. But this time we use ‘id’ and ‘pk=id’. Again we the ‘.save()’ method to update the model. It is important to use ‘instance=post’ so that the ‘else’ part of the if statement return the current instance of the model ‘Members’ to ‘edit.html’, otherwise we will have a blank form and nothing to edit.
Django then passes the dictionary {‘form’:form} to ‘member_edit.html’ and everything after that works the same as it did when we used the from to create an instance of the model ‘Members’.
This completes the ‘U’ for ‘update’ in CRUD.