Tell me how to display the following form in the Django template: Result

models.py

from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver from django.utils.translation import gettext_lazy as _ from .util import image_file_name class SpecializationGroup(models.Model): name = models.CharField(max_length=250, verbose_name=_('Название')) def __str__(self): return self.name class Meta: verbose_name = _('Группа специализации') verbose_name_plural = _('Группы специализаций') class Specialization(models.Model): name = models.CharField(max_length=250, verbose_name=_('Название')) group = models.ForeignKey(SpecializationGroup, verbose_name=_('Группа')) def __str__(self): return self.name class Meta: verbose_name = _('Специализация') verbose_name_plural = _('Специализации') class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, verbose_name=_('Пользователь')) birthDate = models.DateField(null=True, blank=True, verbose_name=_('Дата рождения')) image = models.ImageField(upload_to=image_file_name, null=True, blank=True, verbose_name=_('Изображение профиля')) phone = models.CharField(max_length=20, null=True, blank=True, verbose_name=_('Номер телефона')) url = models.URLField(max_length=250, null=True, blank=True, verbose_name=_('Веб сайт')) town = models.ForeignKey(Towns, null=True, blank=True, verbose_name=_('Город')) status = models.ForeignKey(Statuses, default=1, verbose_name=_('Статус')) summary = models.TextField(null=True, blank=True, verbose_name=_('Резюме')) skype = models.CharField(max_length=100, null=True, blank=True, verbose_name='Skype') specializations = models.ManyToManyField(Specialization, blank=True, verbose_name='Специализации') def __str__(self): return self.user.username class Meta: verbose_name = _('Профиль пользователя') verbose_name_plural = _('Профили пользователей') 

forms.py

 from django import forms from django.contrib.auth.models import User from .models import * class SpecializationForm(forms.ModelForm): specializations = forms.ModelMultipleChoiceField(queryset=Specialization.objects.all(), widget=forms.CheckboxSelectMultiple()) class Meta: model = UserProfile fields = ('specializations',) 

    1 answer 1

    To begin with, it is necessary to sort the specializations in the form into groups:

     specializations = forms.ModelMultipleChoiceField(queryset=Specialization.objects.all().order_by('group'), widget=forms.CheckboxSelectMultiple()) 

    In the next step, you can loop through the objects from the queryset in the template.

    Template example:

     {% for choice in form.mychoices.field.queryset %} {% ifchanged choice.group %} <label>{{ choice.group.name }}</label> {% endifchanged %} <label> <input type="checkbox" name="specializations" value="{{ choice.id }}"> {{ choice.name }} </label> {% endfor %} 

    Or, you can do the following:

     {% for choice in form.mychoices.field.choices %} {{ choice.0 }} {% endfor %} 

    Similar task

    • This is what I was looking for, thanks for the help !! The only question is how with this output to check whether the element was selected earlier or not? The checked property which is in the attributes of the form is not available if we cycle through the queryset? - Igor
    • There is an option via form.my_choice_field.field.choices , it is described here . - Sergey Chabanenko