我不确定这是否是最干净的编辑方式。但经过数小时的研究,这是我能想到的最好的。但是,我不喜欢我必须将 id 存储在隐藏字段中才能再次将其作为 POST 检索以实际更新模型的事实。
有没有更有效的方法来做到这一点?
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('/')