0
我想使用表單更新模型條目。問題在於不是更新條目而是創建一個新條目。使用表單的Django更新模型條目失敗
def edit(request, c_id):
instance = get_object_or_404(C, id=int(c_id))
if request.POST:
form = CForm(request.POST, instance=instance)
if form.is_valid():
form.save()
return redirect('/a/b', c_id)
else:
form = CForm(instance=instance)
args = {}
args.update(csrf(request))
args['form'] = form
args['c_id'] = c_id
return render_to_response('a/b.html', args)
HTML代碼:
<form action="https://stackoverflow.com/a/edit/{{ c_id }}/" method="post">
{% csrf_token %}
{% for field in form %}
<div class="fieldWrapper">
{{ field.errors }}
{{ field.label_tag }} {{ field }}
{% if field.help_text %}
<p class="help">{{ field.help_text|safe }}</p>
{% endif %}
</div>
{% endfor %}
<input type="submit" value="Submit"/>
</form>
的CForm類代碼
class CForm(forms.ModelForm):
class Meta:
model = C
fields = ['name', 'code']
請更新您正在使用來渲染表單的HTML您的問題。 – Soviut
@Soviut我已經更新了 – spoke
@Alasdair我已經添加了CForm類 – spoke