[Django]-Django, how to include pre-existing data in update form view

3👍

You passed the instance argument on POST, but not on GET.

form = UpdateSomethingForm(instance=instance)

in full:

def update_something(request, object_pk):
    try:
        instance = Something.objects.get(pk=object_pk)
    except Something.DoesNotExist:
        instance = None
    if request.method == 'POST':
        form = UpdateSomethingForm(request.POST, instance=instance)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/home')
    else:
        form = UpdateSomethingForm(instance=instance)
    context_dict = {'form': form, 'instance': instance}
    return render(request, 'form.html', context_dict)

1👍

The main problem is that you construct an empty Form, even if the instance can be found. But you make the view rather “chaotic” in the first place.

Probably a more readable view is:

def update_something(request, object_pk):
    context_dict = {}
    try:
        instance = Something.objects.get(pk=object_pk)
    except Something.DoesNotExist:
        instance = None
    context_dict['instance'] = instance
    if request.method == 'POST':
        form = UpdateSomethingForm(request.POST, instance=instance)
        if form.is_valid():
            form.save(commit=True)
            return redirect('view_name')
    else:
        form = UpdateSomethingForm(instance=instance)
    context_dict['form'] = form
    return render(request, 'form.html', context=context_dict)

Here we ensure that the instance variable is always defined, also in the case the except body is “firing”.

Furthermore it is probably better to use a redirect(..) and pass the name of the view over an URL, since if you change the URL of that view, this will still work.

Leave a comment