Django-registration ajax post form

时间:2016-02-17 15:53:21

标签: ajax django django-registration

注册并进行验证我将通过Ajax提交表单。

我检查了其他帖子并尝试了一些选项,但csrf_token给出了jscript错误

Uncaught SyntaxError: Unexpected identifier

表单用于登录,如果数据输入正常,表单即使出现错误也会提交。但是如果输入的数据是错误的,那就什么都不做。

$(document).on("submit", this.id, function(e) {
  e.preventDefault();
  var frm     = e.target.id;
  var frmData = $("#"+frm).serialize();
  $.ajax({
     type: "POST",
      url: '{% url 'django.contrib.auth.views.login' %}',
     contentType: 'application/x-www-form-urlencoded;charset=utf-8',
     csrfmiddlewaretoken : '{% csrf_token %}',
     data: frmData,
     success: function(data)
      {
      console.log('success');
        },
     error: function (data) {
      console.log('error');}
   }); 

我在表单中也有csrf_token标记。

1 个答案:

答案 0 :(得分:0)

我认为这可以解决您的问题:

// ajax components
    function getCookie(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    };
    var csrftoken = getCookie('csrftoken');
    function csrfSafeMethod(method) {
        // these HTTP methods do not require CSRF protection
        return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
    }
    $.ajaxSetup({
        beforeSend: function(xhr, settings) {
            if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
                xhr.setRequestHeader("X-CSRFToken", csrftoken);
            }
        }
    });

我的表格看起来像是什么:

<ul class="sub-menu collapse" id="settings">
    <form id="glucose_boundary_form" action="/glucose/goals" method="POST">
        {% csrf_token %}
        {{ glucose_boundary_form.as_p }}
    </form>
    <button type="submit" id="glucose_goals">Submit</button>
</ul>

按钮点击是什么样的

$('button#glucose_submit').click(function() {
        $.ajax({
            url:'glucose/submit',
            type: 'POST',
            data: $('form#glucose_form').serialize(),
            success: function(data) {
                document.getElementById("glucose_form").reset();
            }
        });
    });

编辑:

这是我的登录和注册视图。虽然我不使用ajax进行注册。表单验证会自动发生在登录页面上。希望他们能帮助你了解我在做什么,以及如何应用我的答案。

from django import forms
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.shortcuts import render
from django.contrib.auth.models import User
from django.contrib.auth import login as auth_login
from django.contrib.auth import logout as auth_logout
from loginregistration.models import loginForm, registrationForm

# Login user method
def login(request):
    if request.user.is_authenticated():
        return HttpResponseRedirect('')
    form = loginForm(request.POST or None)
    if request.POST and form.is_valid():
        user = form.login(request)
        if user:
            auth_login(request, user)
            return HttpResponseRedirect('/')  # Redirect to a success page.
    return render(request, 'login.html', {'form': form})

# Logout user method
def logout(request):
    auth_logout(request)
    return HttpResponseRedirect(reverse('loginregistration.views.login'))  # Redirect to a success page.

# Register user method
def register(request):
    if request.user.is_authenticated():
        return HttpResponseRedirect('/')

    if request.method == 'POST':                    # If the form has been submitted...
        form = registrationForm(request.POST)       # A form bound to the POST data
        if form.is_valid():                         # All validation rules pass
            first_name  = form.cleaned_data['first_name']
            last_name   = form.cleaned_data['last_name']
            password    = form.cleaned_data['password']
            username    = form.cleaned_data['username']
            email       = form.cleaned_data['email']

            # Tries to create a new user and add them to the database
            try:
                User.objects.create_user(username, email=email, password=password, first_name=first_name, last_name=last_name)
            except:
                #Add error
                return HttpResponseRedirect('#ERROR')
            return HttpResponseRedirect('/login')  # Redirect after POST
    else:
        form = registrationForm()  # An unbound form

    return render(request, 'register.html', {'form': form})

这是我的登录模板:

 {% extends "base.html" %}
{% block title %}Login{% endblock %}

{% block content %}

    <form method="post" action="" id="login" class="container" 
        style="background-color: #FFFFFF; max-width: 450px; border-radius: 8px;">
        {% csrf_token %}
        <h1 style="text-align: center">Login to Your Account</h1>
        <div class="form-group container" style="max-width: 300px;">
            {{form.as_p}}
            <button type="submit" class="btn btn-primary">Login</button>
            <a href="/register" type="button" class="btn btn-default pull-right">Create an account</a>
        </div><br>
    </form>
    <script type="text/javascript">document.forms.login.id_username.focus();</script>

{% endblock %}

这是我的注册模板:

{% extends "base.html" %}
{% block title %}Create Account{% endblock %}

{% block content %}

    <form method="post" action="" id="register" class="container " 
        style="background-color: #FFFFFF; max-width: 450px; border-radius: 8px;">
        {% csrf_token %} 
        <h1 style="text-align: center">Register for an Account</h1>
        <b></b>
        <p style="text-align: center">WARNING: This is a prototype website for testing purposes only. For security reasons, do not use your real credentials!</p>
        <div class="form-group container" style="max-width: 300px;">
            {{form.as_p}}
            <button type="submit" class="btn btn-primary btn-block">Create The Account</button>
        </div>
    </form>
    <script type="text/javascript">document.forms.register.id_firstName.focus();</script>

{% endblock %}