Answer the question
In order to leave comments, you need to log in
How in Django template to display in the form (in the SELECT section) through {% for, values from ForeignKey?
There is a simple model:
class ModelPi(models.Model):
material = models.ForeignKey(Material, on_delete=models.PROTECT)
title = models.CharField(max_length=50, unique=True)
is_active = models.BooleanField(default=True)
priority = models.IntegerField(default=0, verbose_name='Приоритет сортировки')
class Material(models.Model):
title = models.CharField(max_length=50, verbose_name="Материал", unique=True)
class ModelPiForm(forms.ModelForm):
class Meta:
model = ModelPi
fields = ['title', 'material', 'priority', 'is_active']
labels = {
'title': 'Название Модели',
'material': 'Материал',
'priority': 'Приоритет сортировки',
'is_active': 'Активна (включена)',
}
help_texts = {
'priority': 'используется для отображения порядка при выборе, чем больше число, тем выше в списке',
'is_active': 'если выключено, то не показывается в каталоге',
}
<div class="md-form mb-0">
<input type="text" id="title" name="title" class="form-control"
value="{{ form.title.value|default_if_none:'' }}">
<label for="title" class="">{{ form.title.label }}</label>
</div>
<select class="mdb-select md-form" id="material" name="material">
<option value="" disabled selected>Выберите материал, нажав здесь</option>
{% for material in form.material %}
<option value="{{ material.id }}">{{ material.title }}</option> ### так не работает!
{% endfor %}
</select>
Answer the question
In order to leave comments, you need to log in
On the advice of respected Pavel Denisov, I began to dig in the direction he suggested. And in the end I came up with the following:
<select class="mdb-select md-form" id="material" name="material">
{% for material in form.material.field.choices.queryset %}
<option value="{{ material.id }}">{{ material.title }}</option>
{% endfor %}
</select>
<select class="mdb-select md-form" id="material" name="material">
{% for material in form.material.field.choices.queryset %}
<option value="{{ material.id }}"
{% if material.id == modelpi.material.id %} selected="selected"{% endif %}
>{{ material.title }}</option>
{% endfor %}
</select>
{% for choice in form.type.field.choices %}
<div class="form-check">
<input type="radio"
class="form-check-input my-change"
id="{{ form.type.name }}_{{ forloop.counter0 }}"
name="{{ form.type.name }}"
value="{{ choice.0 }}"{% if choice.0 == additionalproperty.type %} checked="checked"{% endif %}>
<label class="form-check-label"
for="{{ form.type.name }}_{{ forloop.counter0 }}">{{ choice.1 }}</label>
</div>
{% endfor %}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question