Editing without using id hidden field in form?
django
Solution
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})
Problem
I am not sure if this is the cleanest way of writing an edit. But after hours of research this is the best I could come up with. However I don't like the fact that I have to store the id inside a hiddenfield just to retrieve it again as POST to actually update the model. Is there a more efficient way of doing this? ``` def edit_contact_view(request): profile = request.user.get_profile() if 'id' in request.GET: try: id = request.GET['id'] contacts = profile.company.contact_set.all() form = ContactsForm(profile.company, instance=contacts.get(id=id)) form.data['id'] = id variables = RequestContext(request, {'form':form }) return render_to_response("contact.html", variables) except Contact.DoesNotExist: raise Http404(_(u'Contact not found')) else: if request.method == 'POST': form = ContactsForm(profile.company, request.POST) if form.is_valid(): contacts = profile.company.contact_set.all() contact = contacts.get(id=form.cleaned_data['id']) contact.last_name = form.cleaned_data['last_name'] contact.save() return HttpResponseRedirect('/') ```