我有一个非常简单的联系我们表格,但success_url不起作用。成功提交表单后,页面不会重定向到主页。
我已按照此处提供的文档https://docs.djangoproject.com/en/1.10/topics/class-based-views/generic-editing/
class ContactFormView(SuccessMessageMixin, FormView):
form_class = ContactForm
template_name = 'contact.html'
success_message = 'Thank you!'
success_url = reverse_lazy('home')
def form_valid(self, form):
form.send_email()
return super(ContactFormView, self).form_valid(form)
正在调用form_valid但是没有发生重定向到sucess_url并且没有错误。
感谢您的帮助。
-------------修订-----------------
forms.py
class ContactForm(forms.Form):
name = forms.CharField(widget = TextInput(attrs={'placeholder': 'Your Name'}))
email = forms.CharField(widget = EmailInput(attrs={'placeholder': 'Email'}))
phone = forms.CharField(widget = TextInput(attrs={'placeholder': 'Phone'}))
comment = forms.CharField(widget = forms.Textarea(attrs={'placeholder': 'Please write a comment'}))
def send_email(self):
# send email using the self.cleaned_data dictionary
print("email sent!")
urls.py
import web.views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^contact/', web.views.ContactFormView.as_view(), name='contact'),
url(r'^$', web.views.home, name='home')
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
contact.html
<div class="as-form">
<form method="post" class="myform" action="{% url 'contact' %}">
{% csrf_token %}
{% if form.errors %}{{ form.errors }}{% endif %}
<p> {{form.name}} </p>
<p> {{form.phone}} </p>
<p> {{form.email}} </p>
<p class="as-comment"> {{form.comment}} </p>
<hr>
<p class="as-submit"> <input type="submit" value="Submit" class="as-bgcolor"> </p>
</form>
</div>
答案 0 :(得分:0)
我不知道你是如何设置的,但下面的工作非常出色(Django 1.10,Python 3.5)
# urls.py
urlpatterns = [
url(r'^$', home_view, name='home'),
url(r'^form/$', ContactFormView.as_view(), name='contact')
]
# forms.py
class ContactForm(forms.Form):
name = forms.CharField(max_length=20)
def send_email(self):
print('Email sent!')
# views.py
# Your ContactFormView as is
# contact.html
<form action="" method="post">{% csrf_token %}
{% if form.errors %}{{ form.errors }}{% endif %}
{{ form.as_p }}
</form>