我在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 %}
答案 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