1

我有一个表单,我想用对象自动填充以进行编辑。

我的表单片段如下:

{% 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 %}

有没有一种简单的方法来创建这样的片段,当它可用于表单时添加对象内容?或者,我是否需要使用明确描述的值重新创建编辑表单?

谢谢!

4

1 回答 1

0

使用initialModelForm

>>> 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>
于 2012-05-27T05:40:01.557 回答