M
M
Maxim Zubenko2018-12-27 20:27:39
Django
Maxim Zubenko, 2018-12-27 20:27:39

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='Приоритет сортировки')

the material model is even simpler:
class Material(models.Model):
    title = models.CharField(max_length=50, verbose_name="Материал", unique=True)

I have a form class:
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': 'если выключено, то не показывается в каталоге',
        }

Those. we see that we have a foreign key on materials.
But the template is very tricky and uses its own classes, JS and other troubles. Therefore, I display all the fields manually. For example, I display the same title field in a similar way:
<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>

But How can I display the values ​​of the material through {% for ... %}, for example, in the SELECT section ?
<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

1 answer(s)
M
Maxim Zubenko, 2018-12-28
@JawsIk

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>

Accordingly, if you need to select the desired option along the way (if this is not an add page, but, for example, an edit page), then another if is added:
<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>

Don't forget to "pass" the model (ModelPi in the example) to the template.
By the way, having paid attention to choices, I tried a similar construction with CHOICES.
In order not to repeat myself, I will show you how to do this with a radio button (radio switches)
It is done similarly, but still:
{% 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 %}

Don't forget to "pass" the model (in the code above it's AdditionalProperty) to the template.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question