简体   繁体   中英

Django model form not submitting correctly

I've created a model form which is then rendered in a context processor as the form is included on every page. Once the form is submitted it should re-direct to a 'thank you' page. However it just seems to re-load the page and remove the form. I had it all working when rendering on a page via a URL. Since moving the function to my context processor it doesn't redirect correctly.

It also saves the information that's provided into the model, in the admin. So I'm guessing it is something to do with redirect.

Here is my context processor:

from django.conf import settings
from contact_enquiries import forms

from django.shortcuts import render
from django.http import HttpResponseRedirect


def contact(request):
    if request.method == 'POST':
        form = forms.ContactUsForm(request.POST)

        if form.is_valid():

            form.save()

        return HttpResponseRedirect('/thanks/')

    else:
        form = forms.ContactUsForm()

        return {
                  'contact_form' : form,
        }

forms.py

class ContactUsForm(ModelForm):
    class Meta:
        model = ContactUs
        fields = ['name', 'contact_number', 'email', 'enquiry']

models.py

class ContactUs(models.Model):
    name = models.CharField(max_length=200)
    contact_number = models.IntegerField(max_length=50)
    email = models.EmailField(max_length=300)
    enquiry = models.TextField()

    class Meta:
        verbose_name_plural = "Contact Us"


    def __unicode__(self):
        return self.name

A context processor should always return a dictionary, it shouldn't return an http response.

One option is to make your contact form post to a different view. You do this by changing the action attribute of the form in your template.

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

Your contact view and url patterns would look something like this:

url('^/contact/$', contact, name="contact"),

def contact(request):
    if request.method == 'POST':
        form = forms.ContactUsForm(request.POST)

        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/thanks/')

    else:
        form = forms.ContactUsForm()

    return render(request, "contact.html", {
              'contact_form' : form,
    })

Your context processor then simplifies to:

def contact(request):
    form = forms.ContactUsForm()
    return {'contact_form' : form}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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