5

我是 Django 的新手,我正在尝试用酥脆的表单来设计表单。我的应用程序中有一个表单,它恰好是一个模型表单,我已经按照这里所说的https://stackoverflow.com/a/13201588/1076075使 ModelForm 与crispy_forms 一起工作,但收到此错误:

'FormHelper' object has no attribute 'append'

这就是我的代码的外观forms.py

from django import forms
from models import Ticket, Ticketuser
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit, Layout, Fieldset, ButtonHolder
from crispy_forms.bootstrap import FormActions

class AddTicketForm(forms.ModelForm):

  def __init__(self, *args, **kwargs):
    super(AddTicketForm, self).__init__(*args, **kwargs)
    self.helper = FormHelper(self)
    self.helper.append(Submit('save', 'save'))

  class Meta:
    model = Ticket
    fields = ('id', 'comment')

  def process(self):
    data = self.cleaned_data
    data = data['comment']
    return data

如何克服这一点并按照我想要的方式设置表单样式?

4

2 回答 2

2

显然,表单助手 api 已更改,您需要使用add_input而不是append现在:

这是直接来自文档的示例:

from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit

class ExampleForm(forms.Form):
    [...]
    def __init__(self, *args, **kwargs):
        super(ExampleForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_id = 'id-exampleForm'
        self.helper.form_class = 'blueForms'
        self.helper.form_method = 'post'
        self.helper.form_action = 'submit_survey'

        self.helper.add_input(Submit('submit', 'Submit'))
于 2013-05-16T07:26:04.913 回答
2

FormHelper从来没有附加方法AFAIK。真正有append按钮的是布局:

self.helper.layout.append(HTML('<p>whatever<p>'))

http://django-crispy-forms.readthedocs.org/en/latest/dynamic_layouts.html#manipulating-a-layout

为此,您需要有一个布局集:

self.helper = FormHelper()
self.helper.layout = Layout('field_1', 'field_2')

或者为您设置默认布局http://django-crispy-forms.readthedocs.org/en/latest/dynamic_layouts.html#formhelper-with-a-form-attached

http://django-crispy-forms.readthedocs.org/en/latest/dynamic_layouts.html#manipulating-a-layout

我在另一个 StackOverflow 示例中有一个错字,这误导了你,对不起。

于 2013-05-16T08:30:57.143 回答