简体   繁体   English

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

[英]django FormView not creating object or redirecting to success_url

trying to implement a django form via class-based FormView and following the docs isn't working for me ( https://docs.djangoproject.com/en/1.11/topics/class-based-views/generic-editing/ . Project is 1.11.9 尝试通过基于类的FormView来实现django表单,并且遵循这些文档对我不起作用( https://docs.djangoproject.com/en/1.11/topics/class-based-views/generic-editing/。Project是1.11.9

models.py 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 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 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 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 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 %}

first, I have a 'thanks' view, but success_url on form submit just calls the redirect view back to home. 首先,我有一个'thanks'视图,但是表单提交上的success_url只是将重定向视图调用回首页。 also tried success_url = reverse_lazy('thanks') but still being redirected back home. 还尝试了success_url = reverse_lazy('thanks')但仍被重定向回首页。 do I need to explicitly overwrite get_success_url for it to work? 我是否需要显式覆盖get_success_url才能正常工作? possibly related, form.save() is not creating a new Contact object in db from form fields. 可能相关, form.save()不会从db字段中的db中创建新的Contact对象。 thanks 谢谢

On the URL /contact (without a trailing slash), <form action="." ...> 在URL /contact (不带斜杠)上, <form action="." ...> <form action="." ...> means the request will be submitted to / . <form action="." ...>表示请求将提交给/

Change the action to specifically post to the contact view: 更改操作以专门发布到联系人视图:

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

Usually, I would suggest you stop making the trailing slash optional, and let Django redirect from /contact to /contact/ . 通常,我建议您停止将尾部斜杠设为可选,并让Django从/contact重定向到/contact/ However this might not work because of your catch-all redirect. 但是,这可能由于您的全部重定向而行不通。

Think carefully about whether you really want this catch-all redirect, it's going to subtlety change Django behaviour. 仔细考虑一下您是否真的想要这种全面的重定向,它将微妙地改变Django的行为。 You almost certainly don't want permanent=True for your redirect - if you add another view in future, browsers will have cached the redirect and continue to redirect to the home page. 几乎可以肯定,您不需要permanent=True进行重定向-如果将来添加另一个视图,浏览器将缓存该重定向并继续重定向到主页。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM