我在模型表单中有一个很多的对象,我希望将它们作为彼此之间的选择字段呈现,但无论我尝试什么,我都会用酥脆的django形式让它们彼此相邻
class ContactForm(forms.ModelForm):
choice = forms.ModelMultipleChoiceField(label=_('Request'), widget=forms.CheckboxSelectMultiple(),required=False,
queryset=ContactFormChoices.objects.all())
name = forms.CharField(label=_('Name'))
email = forms.EmailField(required=False, label=_('E-mail'))
phone_number = forms.CharField(required=False, label=_('Phone number'))
message = forms.CharField( widget=forms.Textarea , label=_('Message'))
def __init__(self, *args, **kwargs):
super(ContactForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_class = 'form-horizontal'
self.helper.layout = Layout(
Field('name', css_class='input-xlarge'),
Field('email', css_class='input-xlarge'),
Field('phone_number', css_class='input-xlarge'),
Field('message', rows="3", css_class='input-xlarge'),
#'choice',
Field('choice'),
FormActions(
Submit('submit', _('Submit'), css_class="btn-primary")
)
)
class Meta:
model = ContactData
fields = ['name','message','email','phone_number','choice']
和模型:
class ContactFormChoices(models.Model):
'''
The contact form options to show
'''
text = models.CharField(max_length=256)
active = models.BooleanField(default=True)
def __unicode__(self):
return self.text
class ContactData(models.Model):
'''
The contact data (when customer fills in the contact form,
this is mailed and saved here
'''
name = models.CharField(max_length=256,help_text=_("Name"))
phone_number= models.CharField(max_length=256,null=True,blank=True,default=None)
email = models.EmailField(max_length=256,null=True,blank=True,default=None)
choice = models.ManyToManyField(ContactFormChoices,blank=True,default=None)
message = models.TextField()
def __unicode__(self):
return self.name
有人有什么建议吗?
答案 0 :(得分:2)
helper.layout = Layout(
Field('name', css_class='input-xlarge'),
Field('email', css_class='input-xlarge'),
Field('phone_number', css_class='input-xlarge'),
Field('message', rows="3", css_class='input-xlarge'),
PrependedText('choice', ''),
FormActions(
Submit('submit', _('Submit'), css_class="btn-primary")
)
)
部分重复此问题并回答:BooleanField checkbox not render correctly with crispy_forms using bootstrap