Найти - Пользователи
Полная версия: как определить в шаблоне, что поле формы ModelForm обязательное?
Начало » Django » как определить в шаблоне, что поле формы ModelForm обязательное?
1
tur75
как определить в шаблоне, что поле формы ModelForm обязательное?
имею форму
class EditFlatSell(forms.ModelForm):
class Meta:
model = FlatSell
в шаблон передаю форму и пишу всякое стандартное:
        {% for field in form %}
<div class="field">
{% if field.errors %}
<span class="error">
{% for error in field.errors %}
{{ error }}<br/>
{% endfor %}
</span>
{% endif %}
{{ field.label_tag }}
{{field}}
{% if field.help_text %}<span class="help">{{ field.help_text }}</span>{% endif %}

</div>
{% endfor %}
работает. но, надо же отметить как-то обязательные поля, т.е. поля с атрибутами blank=False или models.ForeignKey в определении модели FlatSell.
не могу понять, как это сделать?
дайте ответ.
Lolka
{% if field.field.required %}*{% endif %}
tur75
Lolka
Код:

{% if field.field.required %}*{% endif %}
да, работает. спасибо.
скажите, Lolka, это в доках где-нить описано? и где это в исходниках Django можно посмотреть? чтобы научиться на будущее самому выплывать.
svas
Еще вариант: у класса формы задать атрибут required_css_class
class EditFlatSell(forms.ModelForm):
class Meta:
model = FlatSell
required_css_class = 'required_field'
В шаблоне все required поля будут с классом required_field
Django Documentation - > Form API - > Styling required or erroneous form rows
Lolka
Я давно когда то задавался этим вопросом. Ответ такой:
{% if field.field.required %}*{% endif %} fragment is the relevant addition here. It adds the asterix only if the field is required.
Note that we check field.field.required and not field.required. In the template, ‘field’ is a newforms.forms.BoundField instance, which holds the actual
'Field' instance in its ‘field’ attribute.
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Powered by DjangoBB