作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想在网站上制作一个 Django 联系表单,我发现 Django 脆皮表单对此非常有用,但事实证明我不能像这样将它与 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 脆皮表单与 Django FormView 一起使用有什么建议吗?
最佳答案
这与脆皮形式没有任何关系。问题出在这段代码中,您将 ContactFormView
视为表单。
def contact(request):
contact_form = ContactFormView()
return render(request, 'myapp/contact.html', {'contact_form': contact_form})
但是,ContactFormView
不是表单,而是基于类的 View 。您不需要定义另一个 View contact
,您已经有一个 View ContactFormView
。
更改您的 url 模式以使用基于类的 View :
url(r'^contact/$', ContactFormView.as_view(), name='contact')
然后在您的模板中包含表单:
{{ form }}}
一旦 View 使用常规表单,请使用 Crispy 标签,以便其样式符合您的意愿:
{% crispy form %}
关于python - 将 Django 脆皮表单与 FormView 混合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28413541/
我是一名优秀的程序员,十分优秀!