Django-带有ModelMultipleChoiceField的表单如何基于其父模型将选择分组?

时间:2019-01-21 14:54:23

标签: python django django-forms django-templates django-views

我想实现的是这样:

Examples of how choices should be categorised

Category1
    Choice1
    Choice2
    Choice3
Category2
    Choice1
    Choice2
Category3
    Choice1
    Choice2
    Choice3

我使用自定义ModelMultipleChoiceField。 问题是我的模板中无法显示它们的类别。相反,它们全都在彼此之间生成。

我的表格.py:

class CustomAmenitiesSelectMultiple(CheckboxSelectMultiple):
    """
    CheckboxSelectMultiple Parent: https://docs.djangoproject.com/en/2.1/_modules/django/forms/widgets/#CheckboxSelectMultiple
    checkbox_select.html: https://github.com/django/django/blob/master/django/forms/templates/django/forms/widgets/checkbox_select.html
    multiple_input.html: https://github.com/django/django/blob/master/django/forms/templates/django/forms/widgets/multiple_input.html
    checkbox_option.html: https://github.com/django/django/blob/master/django/forms/templates/django/forms/widgets/checkbox_option.html
    input_option.html: https://github.com/django/django/blob/master/django/forms/templates/django/forms/widgets/input_option.html

    """
    template_name = "forms/widgets/custom_checkbox_select.html"
    option_template_name = 'forms/widgets/custom_checkbox_option.html'


class AmenitiesForm(ModelForm):
    class Meta:
        model = Venue
        fields = ('choices',)

    choices = forms.ModelMultipleChoiceField(Amenity.objects.all(), widget=CustomAmenitiesSelectMultiple,)

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        if kwargs.get('instance'):
            initial = kwargs.setdefault('initial', {})
            initial['choices'] = [c.pk for c in kwargs['instance'].amenity_set.all()]

        forms.ModelForm.__init__(self, *args, **kwargs)

    def save(self, commit=True):
        instance = forms.ModelForm.save(self)
        instance.amenity_set.clear()
        instance.amenity_set.add(*self.cleaned_data['choices'])
        return instance

custom_checkbox_option.html:

{% if widget.wrap_label %}
<label{% if widget.attrs.id %} for="{{ widget.attrs.id }}"{% endif %}>{% endif %}{% include "django/forms/widgets/input.html" %}{% if widget.wrap_label %} {{ widget.label }}</label>
{% endif %}

custom_checkbox_select.html

{% with id=widget.attrs.id %}
<div class="inline field">
    <div {% if id %} id="{{ id }}" {% endif %}{% if widget.attrs.class %} class="{{ widget.attrs.class }}" {% endif %}>
        {% for group, options, index in widget.optgroups %}{% if group %}
        <div>
            {{ group }}
            <div>
                {% if id %} id="{{ id }}_{{ index }}" {% endif %}>{% endif %}{% for option in options %}
                <div class="checkbox">{% include option.template_name with widget=option %}</div>
                {% endfor %}{% if group %}
            </div>

        </div>
        {% endif %}{% endfor %}
    </div>
</div>

{% endwith %}

我的模型。py:

class AmenitiesCategory(TimeStampedModel):

    category = models.CharField(max_length=250)
    description = models.TextField()

    def __str__(self):
        return self.category


class Amenity(TimeStampedModel):
    category = models.ForeignKey(AmenitiesCategory, on_delete=models.CASCADE)
    venues = models.ManyToManyField(Venue, blank=True)
    space = models.ManyToManyField(Space, blank=True)
    name = models.CharField(max_length=250)
    description = models.TextField()

    def __str__(self):
        return self.name

    class Meta:
        ordering = ['category']

class Venue(TimeStampedModel):
    """
    Main Venue Model
    ################
    PhoneNumberField() is based on a 3rd-party-app called: Django-Phonenumber-Field
    """
    owner = models.ForeignKey(User, on_delete=models.CASCADE)
    name = models.CharField(max_length=250)
    type = models.ForeignKey(VenueType, on_delete=models.CASCADE)
    total_capacity = models.PositiveIntegerField(default=0)
    description = models.TextField(blank=False)
    contact_number = PhoneNumberField(blank=True)
    contact_email = models.EmailField(blank=True)
    published = models.BooleanField(default=False)

    def __str__(self):
        return self.name

在custom_checkbox_select.html的自定义模板中,我可以看到django用来生成选择的整个循环。我还看到了{{group}}和widget.optgroups(我不知道它们是从哪里来的?我也找不到其他解释这一问题的答案),这也许可以解决这个问题。

0 个答案:

没有答案