刚开始在Django中使用crispy表单,到目前为止它真棒!但是我遇到了以下问题:
每当我尝试在我的视图中操作我的助手时,如下所述:https://django-crispy-forms.readthedocs.org/en/d-0/tags.html,我得到以下TypeError:' ContactForm'对象不可调用。
forms.py
1 from django import forms
2 from django.core.urlresolvers import reverse, reverse_lazy
3 from .models import Contact
4 from django.utils.translation import ugettext_lazy as _
5
6 from crispy_forms.helper import FormHelper
7 from crispy_forms.layout import Submit
8
9
10 class ContactForm(forms.ModelForm):
11
12 def __init__(self, *args, **kwargs):
13 self.helper = FormHelper()
14 self.helper.add_input(Submit('add_contact', 'Add contact'))
15 self.helper.show_errors = True
16 self.helper.form_action = reverse_lazy('contacts:create_contact')
17 super(ContactForm, self).__init__(*args, **kwargs)
18
19 class Meta:
20 model = Contact
21 fields = ['title']
views.py
2 from __future__ import absolute_import, unicode_literals
3
4 from django.core.urlresolvers import reverse, reverse_lazy
5 from django.views.generic import DetailView, ListView, RedirectView, UpdateView, FormView
6 from django.views.generic.edit import CreateView
7 from django.contrib.auth.decorators import login_required
8 from django.shortcuts import render
9
10 from braces.views import LoginRequiredMixin
11 from .forms import ContactForm
12 from .models import Contact
13
14
20 class CreateContactView(LoginRequiredMixin, CreateView):
21 template_name = 'contacts/contact_form.html'
22 form_class = ContactForm()
23 form_class.helper.form_action = ""
23 model = Contact
24 success_url = reverse_lazy('contacts:list_contacts')
你们知道我做错了什么吗?如何使这个表格可以调用?显然错误从我视图的第22行开始,我可以通过删除第23行并删除第22行的括号来解决它,但如果我想更改helper.form_action,我必须这样做。
答案 0 :(得分:1)
在基于类的视图中设置form_class
时,必须使用类,而不是实例。
class CreateContactView(LoginRequiredMixin, CreateView):
template_name = 'contacts/contact_form.html'
form_class = ContactForm
当服务器启动时,此代码将加载一次。
如果要更改帮助程序,则需要在视图的方法中编辑表单实例。每个请求都会运行一次此代码。例如,您可以覆盖get_form
。
class CreateContactView(LoginRequiredMixin, CreateView):
template_name = 'contacts/contact_form.html'
form_class = ContactForm
def get_form(self, form_class=None):
form = super(CreateContactView, self).get_form(form_class)
form.helper.form_action = ""
return form
但是,对于您给出的示例,更容易在表单的__init__
方法中设置操作。那么您也不必重写get_form
方法。
class ContactForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
self.helper = FormHelper()
self.helper.form_action = ""
...
答案 1 :(得分:0)
问题出在您form_class
的{{1}}定义中。使用基于类的视图时,您不必实例化它(即CreateContactView
)。您需要将其更改为:
ContactForm()