django2中用于ajax的csrf令牌 [英] csrf token for ajax in django2

查看:103
本文介绍了django2中用于ajax的csrf令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习Django2,并尝试使用csrf_token和ajax创建登录页面.

I am learning Django2,and try to make a login page with csrf_token and ajax.

我希望如果用户还没有登录,那将转到登录页面并在登录之前发送变量 next 作为该页面的标签.如果用户成功登录,我可以转到 next 标记的首页或页面.

I hope that if user hasn't lgoin,that will turn to the login page and send a variable next as a tag of the page before login.If user login successfully that I can turn to the homepage or page marked by next.

我阅读了Django2的文档,并尝试编写如下代码,但是,当我单击登录"按钮时,它只是刷新登录页面而没有错误

I read the docs of Django2, and try to code like below,however,when I click "LOGIN" button,it just refresh the login page and get no error

我很困惑,还不知道.请帮助.

I am confused and have no idea already.Please help.

登录视图:

def login(request):
    if request.is_ajax():
        uf = UserForm(request.POST)
        if uf.is_valid():
            # get info from form
            username = uf.cleaned_data['username']
            password = uf.cleaned_data['password']
            user = auth.authenticate(request, username=username, password=password)
            if user is not None:  # user match
                auth.login(request, user)
                if request.GET.get('next'):
                    next_url = request.GET.get('next')
                    return JsonResponse({'redirect_url': next_url})
                    # return redirect(request.GET.get('next'))
                else:
                    return JsonResponse({'redirect_url': 'home'})
            else:  # user not match
                error_msg = ["username or pwd mistake"]
                return JsonResponse({'error_msg': error_msg})
    else:
        uf = UserForm()
    return render(request, 'login.html', {'uf': uf})

html:

    <form>
      {% csrf_token %}
       {{ uf.username }}
       {{ uf.password }}
      <div id="errorMsg"></div>
        <button type="submit" class="btn btn-default" id="loginButton">login</button>
     <input type="hidden" name="next" id="redirect-next" value="{{ next|escape }}"/>
   </form>

jQuery:

       $("#loginButton").click(function () {
    $.ajax({
        url: "",
        type: 'POST',
        dataType: "json",
        data: {username: $("#inputEmail3").val(), password: $("#inputPassword3").val()},
        beforeSend: function (xhr, settings) {
            var csrftoken = Cookies.get('csrftoken');
            function csrfSafeMethod(method) {
                // these HTTP methods do not require CSRF protection
                return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
            }
            if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
                xhr.setRequestHeader("X-CSRFToken", csrftoken);
            }
        },
        success: function (result) {
            if (result.error_msg) {
                $('#errorMsg').show().text('user info error') //print an alert on the page
            }
            else {
                location.href = result.redirect_url //turn to homepage or page before login
            }
        }
    })
});

推荐答案

您无需费心编写自己的登录视图.Django提供了更简单的方法来实现它.

You don't need to take effort to write a login view of your own like this. Django provides easier methods to implement it.

首先请确保您的 settings.py

MIDDLEWARE_CLASSES = [
    ...
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    ...
]
INSTALLED_APPS = [
    ...
    'django.contrib.auth',
    'django.contrib.contenttypes',
    ...
]

将所有登录URL添加到主 urls.py :

Add all the login URLs to your main urls.py:

from django.urls import path
from django.conf.urls import include


urlpatterns = [
....
    path('accounts/', include('django.contrib.auth.urls')),
....
]

不要忘记运行 python manage.py migration 来创建 auth 应用程序所需的表.现在已经准备好应用程序和URL,需要创建模板.该应用程序的所有模板都应放置在 templates 目录下名为 registration 的文件夹下.目录结构应类似.

Don't forget to run python manage.py migrate to create the tables required for the auth app. Now that the app and URLs are ready, templates need to be created. All the templates for the app should be placed under a folder named registration under your templates directory. The directory structure should be something like.

your_django_app/
    templates/
        registration/
            login.html
    __init__.py
    apps.py
    settings.py
    urls.py
    views.py
    wsgi.py

login.html 的内容应类似于:

<form id="loginform" action="{% url 'login' %}" method="POST">
{% csrf_token %}
{% if next %}
    <input type="hidden" name="next" value="{{ next }}" />
{% endif %}
    <input name="username" id="id_username" type="text">
    <label>Username</label>
    <input name="password" id="id_password" type="password">
    <label>Password</label>
{% if form.errors %}
    Error! Wrong credentials.
{% endif %}
    <button type="submit">Login</button>
</form>

在此之后,将它们包括在您的 settings.py 文件中,以便在登录后正确重定向用户.

After this include these in your settings.py file for redirecting users correctly after login.

LOGIN_REDIRECT_URL = '/'
LOGIN_URL = '/accounts/login'

您都准备好了.在尝试进行此操作之前,请确保至少创建一个用户,方法是运行 python manage.py createsuperuser .对于需要用户在查看之前登录的所有页面,可以在其相应视图功能上方使用 @login_required 装饰器,以在显示页面之前将其重定向到登录页面.示例:

You are all set to go. Make sure to create at least one user before trying this out by running python manage.py createsuperuser. For all pages that require users to login before viewing them you can use the @login_required decorator above their respective view functions to redirect them to the login page before showing the page. Example:

from django.shortcuts import render
from django.contrib.auth.decorators import login_required

@login_required
def home(request):
    return render(request, 'home/index.html')

这篇关于django2中用于ajax的csrf令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆