是否可以将一些属性写入模型字段,以后可以用它来区分模板中的不同字段?
model.py
from django.db import models
class Person(models.Model):
first_name = models.CharField("i am the Label", max_length=30)
last_name = models.CharField("i am other Label", max_length=30, customattr="Custom")
forms.py
class PersonForm(ModelForm):
class Meta:
Person
template.html
<form action="" method="post">{% csrf_token %}
{% for field in form %}
{% ifequal field.customattr 'Custom' %} # HOW COULD THIS WORK?
<p>Hello world.</p>
{{ field }}
{% else %}
<p>This is not Custom</p>
{{ field }}
{% endifequal %}
{% endfor %}
<input type="submit" value="Submit" />
</form>
任何提示?
答案 0 :(得分:0)
不太可能;模板代码中的field
是表单字段,而不是模型字段。我会将表示逻辑从模型转移到模板中,并执行以下操作:
<form action="" method="post">{% csrf_token %}
{% for field in form %}
{% if field.name == 'last_name' or field.name == 'another_field' %}
<p>Hello world.</p>
{{ field }}
{% else %}
<p>This is not Custom</p>
{{ field }}
{% endif %}
{% endfor %}
<input type="submit" value="Submit" />
</form>
(在Django 1.2中添加了== operator)
答案 1 :(得分:0)
我不明白你为什么要这样做。如果您想为ModelForm字段定义自定义html,可以像这样覆盖它:
class PersonForm(ModelForm):
class Meta:
Person
first_name = forms.CharField(
required = True,
widget = forms.TextInput(attrs={'style':'width:100px;'},
)
像这样你可以告诉Django你想如何呈现你的HTML。 您可以在文档https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#overriding-the-default-field-types-or-widgets
中找到更多详细信息