我目前正在制作一个表单,其中我将多对多关系显示为复选框。现在我知道如何将一个类添加到单个字段,但如何将一个类添加到多对多字段的每个复选框?有 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)
这是一个外键,但我认为它没有任何区别)
最佳答案
您可能需要添加一个自定义类来扩展 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
当然,你可以随意命名类。希望对您有所帮助。
关于python - 将 css 类从数据库添加到 manytomany 字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22629874/