我正在编辑表单,它正确加载数据当我点击保存时它会在数据库中创建新条目。
这是视图函数
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,
})
我是否真的需要具有单独的编辑功能和单独的删除功能。我可以在一个功能中完成所有操作吗
模板
<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>
答案 0 :(得分:14)
您错过了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,
})
答案 1 :(得分:1)
你尝试过这样的事吗?
# Create a form to edit an existing Object.
a = Account.objects.get(pk=1)
f = AccountForm(instance=a)
f.save()
# Create a form to edit an existing Article, but use
# POST data to populate the form.
a = Article.objects.get(pk=1)
f = ArticleForm(request.POST, instance=a)
f.save()