django FormView没有创建对象或重定向到success_url

时间:2018-11-14 17:24:39

标签: django django-forms django-views django-class-based-views

尝试通过基于类的FormView实现django表单并遵循文档对我不起作用(https://docs.djangoproject.com/en/1.11/topics/class-based-views/generic-editing/。项目为1.11.9

models.py

class Contact(models.Model):
    name = models.CharField(max_length=100)
    company = models.CharField(max_length=100)
    email = models.EmailField(unique=True)
    message = models.TextField()
    date_created = models.DateField(verbose_name="Created date", auto_now_add="True")

forms.py

from django import forms

from .models import Contact

class ContactForm(forms.ModelForm):

    class Meta:
        model = Contact
        labels = {
            'company': 'Company or Organization'
        }
        exclude = ('date_created',)

views.py

from django.shortcuts import render
from django.core.mail import send_mail
from django.views.generic import FormView, TemplateView

from .forms import ContactForm

class ContactFormView(FormView):

    form_class = ContactForm
    template_name = "contact.html"
    success_url = '/thanks/'

    def form_valid(self,form):
        message = "{name} from {company} / {email} said: ".format(
            name=form.cleaned_data.get('name'),
            company=form.cleaned_data.get('company'),
            email=form.cleaned_data.get('email'))
        message += "\n\n{0}".format(form.cleaned_data.get('message'))
        send_mail(
            subject='new message',
            message=message,
            from_email='foo@bar.com',
            recipient_list=['foo@blah.com',]
        ) 
        form.save()
        return super(ContactFormView, self).form_valid(form)

urls.py

from django.conf.urls import url
from django.views.generic import TemplateView

from . import views

from .views import ContactFormView


urlpatterns = [
    url(r'^contact/?$', ContactFormView.as_view(), name="contact"),
    url(r'^thanks/?$', views.thanks, name="thanks"),
    url(r'^.*$', RedirectView.as_view(url=reverse_lazy('index'), permanent=True), name='home')

]

contact.html

{% extends 'base.html' %}
{% load humanize %}

{% block title %}Contact Us{% endblock %}

{% block content %}
<div class="wrapper">
  <div id="content" class="container push-half">
     <div class="col-lg-12">

         <h1>Contact</h1>

         <p class="push">Please use the form below to send us a message, and we'll get back to you as soon as we can.</p>
          <div class="push cf">
              <form action="." method="post" class="contact-form">
                      {% csrf_token %}
                      {{ form }}
                      <div class="clearfix"></div>
                      <input type="submit" value="Submit" id="contact-submit-btn" class="btn" />
              </form>
          </div>    
      </div>
  </div>
</div>
{% endblock %}

首先,我有一个'thanks'视图,但是表单提交上的success_url只是将重定向视图调用回首页。也尝试了success_url = reverse_lazy('thanks'),但仍被重定向回首页。我需要显式覆盖get_success_url才能正常工作吗?可能相关,form.save()不在数据库中通过表单字段创建新的Contact对象。谢谢

1 个答案:

答案 0 :(得分:0)

在URL /contact(不带斜杠)上,<form action="." ...>表示请求将被提交到/

更改操作以专门发布到联系人视图:

<form action="{% url 'contact' %}" method="post" class="contact-form">

通常,我建议您停止使斜杠成为可选,并让Django从/contact重定向到/contact/。但是,这可能由于您的全部重定向而行不通。

请仔细考虑您是否真的想要这种全面重定向,它将细微更改Django的行为。几乎可以肯定,您不需要permanent=True进行重定向-如果将来添加另一个视图,浏览器将缓存该重定向并继续重定向到主页。