在'django中使用crispy_forms时,'FormHelper'对象没有属性'append'

时间:2013-05-16 07:07:59

标签: python django django-forms django-crispy-forms

我是Django的新手,我正在尝试用酥脆的形式设计表单。我的应用程序中有一个表单恰好是一个模型表单,我已经按照https://stackoverflow.com/a/13201588/1076075中的说法使模型表单与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

如何克服这个问题,并按照我想要的方式设置表单样式?

2 个答案:

答案 0 :(得分:2)

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

这里的示例直接来自the docs

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'))

答案 1 :(得分: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示例中有一个错字,误导了你,抱歉。