简体   繁体   中英

How to fire a Javascript alert and then redirect the page after user clicks 'ok' in Django?

I have contact form on my Django website. When someone clicks submit, I would like to use a Javascript alert to inform them that their message has been sent and then redirect them to back to the homepage. I've setup the HttpResponseRedirect part in my view, but I'm struggling to get the JS piece working alongside. Here is my views.py:

from datetime import date
from django.http import HttpResponse, HttpResponseRedirect
from django.template import RequestContext
from django.shortcuts import render_to_response
from .form import ContactUsForm

def contact(request):
    form = ContactUsForm(request.POST or None)
    if form.is_valid():
        this_form = form.save(commit=False)
        this_form.save()
        return HttpResponseRedirect('/')

    return render_to_response('contact/form.html', locals(), context_instance=RequestContext(request))

In your template, you could use something as simple as this (uses some jQuery):

$(function()
{
    $('form').on('submit', function(){
        alert('Your message has been sent!');
    });
});

Note a few things:

  1. This is a little misleading, as it alerts the user that their message has been sent, even if it doesn't actually get sent (it never checks with the server to make sure). So, if there was some error in the form, this would definitely mislead the user.

  2. This alert will bind to any form on the page, so it may be better to target the specific form with its id.

So that's the quick-and-dirty solution. I'd recommend, though, using Django's messages framework instead. Basically, you'd not use any Javascript to submit the form, but instead add something like this to your view:

from django.contrib import messages
messages.success(request, 'Message sent.')

And then in your template (best to add this to your base template so it shows up wherever the user goes, since messages expire with every page-load:

{% if messages %}
<ul class="messages">
    {% for message in messages %}
    <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
    {% endfor %}
</ul>
{% endif %}

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