Ran*_*ngh 10 python forms django
我正在编辑表单,它正确加载数据当我点击保存时它会在数据库中创建新条目.
这是视图功能
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,
})
Run Code Online (Sandbox Code Playgroud)
-
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,
})
Run Code Online (Sandbox Code Playgroud)
我是否真的需要具有单独的编辑功能和单独的删除功能.我可以在一个功能中完成所有操作
模板
<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>
Run Code Online (Sandbox Code Playgroud)
Wol*_*lph 15
你错过了instance该POST部分的论点.
而不是这个:
form = AccountForm(request.POST, request.FILES) # A form bound to the POST data
Run Code Online (Sandbox Code Playgroud)
你应该用这个:
form = AccountForm(request.POST, request.FILES, instance=f) # A form bound to the POST data
Run Code Online (Sandbox Code Playgroud)
将其添加到添加/编辑表单后,您就可以同时添加/编辑.
它将添加if instance=None和update if是否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,
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6978 次 |
| 最近记录: |