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('/')