你能帮我修一下这个表格吗

时间:2019-07-01 11:59:45

标签: django-forms

我正在尝试在django表单上添加一个CheckBox Option值,我试图获得最好的值,但仍然出问题了,表单无法正常工作。

没有错误,但未提交表单。

以下是文件以及我得到的内容:

forms.py

from itertools import groupby
from django import forms
from django.forms.models import ModelChoiceIterator, ModelMultipleChoiceField
from .models import Event, Feature, FeatureCategory

class GroupedCheckboxSelectMultiple(forms.CheckboxSelectMultiple):

    def optgroups(self, name, value, attrs=None):
        """
        The group name is passed as an argument to the ``create_option`` method (below).

        """
        groups = []
        has_selected = False

        for index, (option_value, option_label) in enumerate(self.choices):
            if option_value is None:
                option_value = ''

            subgroup = []
            if isinstance(option_label, (list, tuple)):
                group_name = option_value
                subindex = 0
                choices = option_label
            else:
                group_name = None
                subindex = None
                choices = [(option_value, option_label)]
            groups.append((group_name, subgroup, index))

            for subvalue, sublabel in choices:
                selected = (
                    str(subvalue) in value and
                    (not has_selected or self.allow_multiple_selected)
                )
                has_selected |= selected
                subgroup.append(self.create_option(
                    name, subvalue, sublabel, selected, index,
                    subindex=subindex, attrs=attrs, group=group_name,
                ))
                if subindex is not None:
                    subindex += 1
        return groups

    def create_option(self, name, value, label, selected, index, subindex=None, attrs=None, group=None):
        """
        Added a ``group`` argument which is included in the returned dictionary.

        """
        index = str(index) if subindex is None else "%s_%s" % (index, subindex)
        if attrs is None:
            attrs = {}
        option_attrs = self.build_attrs(self.attrs, attrs) if self.option_inherits_attrs else {}
        if selected:
            option_attrs.update(self.checked_attribute)
        if 'id' in option_attrs:
            option_attrs['id'] = self.id_for_label(option_attrs['id'], index)
        return {
            'name': name,
            'value': value,
            'label': label,
            'selected': selected,
            'index': index,
            'attrs': option_attrs,
            'type': self.input_type,
            'template_name': self.option_template_name,
            'wrap_label': True,
            'group': group,
        }

class EventEditForm(forms.ModelForm):
    class Meta:
        model = Event
        fields = ('title', 'user_id', 'manager_prf', 'details', 'runtime', 'category','manager', 'tickets', 'tickets_price', 'evyturl', 'city', 'country', 'status', 'venue', 'tickets_price_currency', 'features','reputation', 'reviews', 'start_date', 'start_hour')

    def __init__(self, *args, **kwargs):
        super(WidgetForm, self).__init__(*args, **kwargs)
        self.fields['features'] = GroupedModelMultipleChoiceField(
            group_by_field='category',
            queryset=Feature.objects.all(),
            widget=GroupedCheckboxSelectMultiple(),
            required=False)

    def clean_fields(self):
        data=self.cleaned_data['fields']
        return data

models.py

class FeatureCategory(models.Model):
    name = models.CharField(max_length=15)

    class Meta:
        ordering = ('-id', 'name') # minus before means descending oreder

    def __str__(self):
        return '{}'.format(self.name)

class Feature(models.Model):
    name = models.CharField(max_length=15)
    category = models.ForeignKey(FeatureCategory, on_delete=models.SET_NULL, null=True, blank=True)

    class Meta:
        ordering = ('-id', 'name', 'category') # minus before means descending oreder

    def __str__(self):
        return '{} ({})'.format(self.name, self.category)

class Event(models.Model):
features = models.ManyToManyField(Feature, blank=True)

file.html

<div class="col-xs-12 col-sm-12 col-md-12">
    <div class="form-group">
      {% regroup form.features by data.group as feature_list %}
{% for group in feature_list %}
<ul>
  {% for choice in group.list %}
  {{ choice }}
  {% endfor %}
</ul>
{% endfor %}
    </div>
</div>

这是它的外观,并且未显示复选框: enter image description here

0 个答案:

没有答案