从模型构建动态表单

时间:2014-10-19 13:34:23

标签: django django-models django-forms django-templates django-views

我在models.py中有以下模型

class TProfiles(models.Model):
    id = models.IntegerField(primary_key=True)  # AutoField?
    first_name = models.CharField(max_length=45, blank=True)
    surname = models.CharField(max_length=45, blank=True)
    email = models.CharField(max_length=45, blank=True)

class Meta:
    managed = False
    db_table = 'profiles'

在我的模板中,我想根据模型属性生成一个表单。有没有办法动态循环它们?

register.html

{% block content %}
    <form enctype="multipart/form-data" action="" method="post">
        <!-- Loop through model attributes here -->
    </form>
{% endblock %}

1 个答案:

答案 0 :(得分:3)

models.py中添加:

class TProfilesForm(ModelForm):
    class Meta:
        model = TProfiles
        fields = ['first_name', 'surname', 'email']

views.py中创建这样的形式:

form = TProfilesForm()

然后将其传递给模板,如下所示:

return render_to_response("register.html", {
    "form": form,
})

在模板中:

{% for field in form %}
    {{ field.label_tag }} {{ field }}
{% endfor %}

另外,您可以找到有关ModelForm here

的所有信息