我想在网站上创建一个Django联系表单,我发现Django crispy表单非常有用,但事实证明我不能将它与Django FormView混合使用。 Crispy表单在前端布局中做了很棒的工作,但是我无法从填充的表单中获取任何信息到我的Django应用程序。我已经尝试过本教程:Simple Django email form using CBV,但它已经过时,根本没用。这是我的forms.py:
from django import forms
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit
class ContactForm(forms.Form):
name = forms.CharField(
label = "Name:",
max_length = 80,
required = True,
)
email = forms.CharField(
label = "E-mail:",
max_length = 80,
required = True,
)
subject = forms.CharField(
label = "Subject:",
max_length = 80,
required = True,
)
message = forms.CharField(
widget = forms.Textarea,
label = "Message:",
required = True,
)
def __init__(self, *args, **kwargs):
super(ContactForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.add_input(Submit('send', 'Send'))
views.py:
from django.shortcuts import render
from myapp.forms import ContactForm
from django.core.mail import send_mail
from django.views.generic.edit import FormView
class ContactFormView(FormView):
form_class = ContactForm
template_name = "myapp/contact.html"
success_url = '/email_sent/'
def form_valid(self, form):
message = "{name} / {email} said: ".format(
name=form.cleaned_data.get('name'),
email=form.cleaned_data.get('email'))
message += "\n\n{0}".format(form.cleaned_data.get('message'))
send_mail(
subject=form.cleaned_data.get('subject').strip(),
message=message,
from_email='contact-form@myapp.com',
recipient_list=['mymail@mydomain.com'],
)
return super(ContactFormView, self).form_valid(form)
def contact(request):
contact_form = ContactFormView()
return render(request, 'myapp/contact.html', {'contact_form': contact_form})
和我的模板contact.html:
{% extends "layout.html" %}
{% load crispy_forms_tags %}
{% block title %}Contact{% endblock %}
{% block content %}
<h2><b>Contact</b></h2>
<div class="container">
<p>You can e-mail me at: <a href="mailto:mymail@mydomain.com">mymail@mydomain.com</a></p>
<br>
<p>Or simply fill the form below:</p>
<br>
{% crispy contact_form %}
</div>
{% endblock %}
我得到的是:
Exception Type: TypeErrorException Value:
'ContactFormView' object is not iterable
有关如何在Django FormView中使用Django crispy表单的任何建议吗?
答案 0 :(得分:2)
这与脆皮表格无关。问题在于这段代码,您将ContactFormView
视为表单。
def contact(request):
contact_form = ContactFormView()
return render(request, 'myapp/contact.html', {'contact_form': contact_form})
但是,ContactFormView
不是表单,而是基于类的视图。您不需要定义另一个视图contact
,您已经拥有了一个视图ContactFormView
。
更改您的网址格式以使用基于类的视图:
url(r'^contact/$', ContactFormView.as_view(), name='contact')
然后在您的模板中,将表单包含在:
中{{ form }}}
一旦视图使用常规表单,请使用crispy标签,以便按照您的意愿设置样式:
{% crispy form %}