我正在编辑表单,它正确加载数据,当我点击“保存”时,它会在数据库中创建新条目。
这是视图函数
def create_account(request):
if request.method == 'POST': # If the form has been submitted...
form = AccountForm(request.POST, request.FILES) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
form.save()
return HttpResponseRedirect('/thanks/') # Redirect after POST
else:
form = AccountForm() # An unbound form
return render_to_response('account_form.html', {
'form': form,
})
--
def edit_account(request, acc_id):
f = Account.objects.get(pk=acc_id)
if request.method == 'POST': # If the form has been submitted...
form = AccountForm(request.POST, request.FILES) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
form.save()
return HttpResponseRedirect('/thanks/') # Redirect after POST
else:
form = AccountForm(instance=f) # An unbound form
return render_to_response('account_form.html', {
'form': form,
})
我真的需要有单独的编辑功能和单独的删除功能吗?我可以在一个功能中完成所有操作吗
template
<form action="/account/" method="post" enctype="multipart/form-data" >
{% csrf_token %}
{% for field in form %}
<div class="fieldWrapper">
{{ field.errors }}
{{ field.label_tag }}: {{ field }}
</div>
{% endfor %}
<p><input type="submit" value="Send message" /></p>
</form>
你错过了instance
论据于POST
部分。
而不是这个:
form = AccountForm(request.POST, request.FILES) # A form bound to the POST data
你应该使用这个:
form = AccountForm(request.POST, request.FILES, instance=f) # A form bound to the POST data
将其添加到添加/编辑表单后,您将能够同时添加/编辑。
它将添加如果instance=None
并更新如果instance
是一个真实的账户。
def edit_account(request, acc_id=None):
if acc_id:
f = Account.objects.get(pk=acc_id)
else:
f = None
if request.method == 'POST': # If the form has been submitted...
form = AccountForm(request.POST, request.FILES, instance=f) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
form.save()
return HttpResponseRedirect('/thanks/') # Redirect after POST
else:
form = AccountForm(instance=f) # An unbound form
return render_to_response('account_form.html', {
'form': form,
})
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)