将css类从数据库添加到manytomany字段

时间:2014-03-25 09:11:06

标签: python css django checkbox

我目前正在制作一个表单,其中我将多对多关系显示为复选框。现在我知道如何将类添加到单个字段但是如何在多对多字段的每个复选框中添加一个类?有3个可能的类,每个复选框应该有数字1-3,就像在数据库中一样,所以我之后可以使用JS。

这是我的表格:

class PersonForm(ModelForm):
    year_range = range(1996, 1920, -1)
    person_password = forms.CharField(widget=forms.PasswordInput(attrs={'class': 'form-control'}))
    person_birthdate = forms.DateField(widget=SelectDateWidget(years=year_range, attrs={'class': 'form-control'}))
    person_password.label = 'Passwort'
    person_birthdate.label = 'Geburtsdatum'
    confirm_password = forms.CharField(widget=forms.PasswordInput(attrs={'class': 'form-control'}))
    class Meta:
        widgets = {'person_interests': forms.CheckboxSelectMultiple,
                   'person_psycho': forms.HiddenInput}
        model = Person

这是我需要类的复选框模型:

class Interest(models.Model):
    interest_id = models.AutoField(primary_key=True)
    interest_name = models.CharField(max_length=100)
    interest_kind = models.ForeignKey(KindOfInterest)
    interest_weight = models.IntegerField()

    def __unicode__(self):
        return self.interest_name

据我所知,我不能在表单中找到attrs={'class': self.id}。那么如何以一种看起来仍然不错并且不需要30行代码的方式访问这些数据呢? (我需要的数据是interest_kind = models.ForeignKey(KindOfInterest)这是一个关键的关键,但我认为它没有任何区别)

1 个答案:

答案 0 :(得分:1)

您可能需要添加一个扩展Django CheckboxSelectMultiple的自定义类,该类可用于M2M关系。您可以在django.forms.widgets找到它。在该课程中,您可以覆盖render方法。

示例:

class BootstrapCheckboxSelectMultiple(CheckboxSelectMultiple):
    """Form widget that supports Bootstrap's markup requirements"""
    def render(self, name, value, attrs=None, choices=()):
        if value is None:
            value = []
        has_id = attrs and 'id' in attrs
        final_attrs = self.build_attrs(attrs, name=name)
        output = []
        # Normalize to strings
        str_values = set([force_unicode(v) for v in value])
        for i, (option_value, option_label) in enumerate(chain(self.choices,
            choices)):

            # If an ID attribute was given, add a numeric index as a suffix,
            # so that the checkboxes don't all have the same ID attribute.

            # Should be able to pass in additional widget attributes to
            # the checkbox renderer here...
            if has_id:
                final_attrs = dict(final_attrs, id='{}_{}'.format(attrs['id'], i))
                label_for = u' for="{}"'.format(final_attrs['id'])
            else:
                label_for = ''

            cb = CheckboxInput(final_attrs,
                check_test=lambda value: value in str_values)

            option_value = force_unicode(option_value)
            rendered_cb = cb.render(name, option_value)
            option_label = conditional_escape(force_unicode(option_label))
            output.append(u'<label{} class="checkbox">{} {}</label>'.format(
                label_for, rendered_cb, option_label))
        return mark_safe(u'\n'.join(output))

然后为您的字段指定类:

class PersonForm(ModelForm):
    ...

    class Meta:
        widgets = {'person_interests': BootstrapCheckboxSelectMultiple,
                   'person_psycho': forms.HiddenInput}
        model = Person

当然,您可以根据需要为课程命名。希望能帮到你。