我有一个表格,我希望自动填充对象进行编辑。
我的表单摘要如下:
{% for field in form %}
<div class="form_block">
{{ field.label_tag }}
{% if field.help_text %}
<p class="help_text">{{ field.help_text }}</p>
{% endif %}
{{ field }}
{% for error in field.errors %}
<p class="error">{{ error }}</p>
{% endfor %}
</div>
{% endfor %}
有没有一种简单的方法来创建这样的代码片段,当对象内容可用于表单时添加它?或者,我是否需要使用明确描述的值重新创建编辑表单?
谢谢!
答案 0 :(得分:0)
使用initial
或ModelForm
>>> from django import forms
>>> from django.contrib.auth.models import *
>>> class UserForm(forms.Form):
>>> username = forms.CharField()
>>> print unicode(UserForm(initial={'username':'foo'}))
<tr><th><label for="id_username">Username:</label></th><td><input type="text" name="username" value="foo" id="id_username" /></td></tr>
>>> class UserModelForm(forms.ModelForm):
>>> class Meta:
>>> model = User
>>> fields = ['username']
>>> print unicode(UserModelForm(instance=User(username='foo')))
<tr><th><label for="id_username">Username:</label></th><td><input id="id_username" type="text" name="username" value="foo" maxlength="30" /><br /><span class="helptext">Required. 30 characters or fewer. Letters, numbers and @/./+/-/_ characters</span></td></tr>