[Django]-Editing without using id hidden field in form?

4👍

Yes, you are making this more complicated than it needs to be.

Firstly, in Django it’s more usual to pass the id in the URL itself, rather than in a GET parameter – eg /contact/edit/3/ rather than /contact/edit?id=3. See for example this question to see how to configure URLs like that.

Secondly, whichever way you do it, there’s no need to pass the id in a hidden variable since it’s already available from the URL. You can always get the instance from there.

Thirdly, I presume that ContactForm is a ModelForm, but you’re not using the save functionality, which simplifies things still further.

Putting it all together:

def edit_contact_view(request, id=None):
    profile = request.user.get_profile()
    if id is not None:
        contact = get_object_or_404(Contact, pk=id)
    else:
        contact = Contact(company=profile.company)
    if request.POST:
       form = ContactForm(request.POST, instance=contact)
       if form.is_valid():
           contact = form.save()
           return redirect(...)

    else:
        form = ContactForm(instance=contact)
    return render_to_response('contact.html', {'form': form})

2👍

I must be missing something here but why don’t you encode the id in the url as is standard?

i.e. in urls.py:

url('^/contact/?P<contact_id>[0-9]+)/edit/$', edit_contact_view, name='edit_contact_view')

your view:

def edit_contact_view(request, contact_id):
    profile = request.user.get_profile()
    contact = get_object_or_404(Contact, id=contact_id)
    if contact not in profile.company.contact_set.all():
        return Http404

and in your template

<form method="POST">
   {{ form.as_p }}
   ...
</form>

Leave a comment