3

表单.html

<form action='/login/' method = 'post'>
    {% csrf_token %}
    <label>Email: (*)</label><input type='text' name='email' value='' /><br />
    <label>Password: </label><input type='password' name='password' value='' /><br />
    <input type='submit' name='submit' value='Log in' />
</form>

和 views.py 我使用 HttpResponse 而不是 render_to_response

def login(request):
    success = False
    message = ''

    try:
        emp = Employee.objects.get(email = request.POST['email'])
        if emp.password == md5.new(request.POST['password']).hexdigest() :
            emp.token = md5.new(request.POST['email'] + str(datetime.now().microsecond)).hexdigest()
            emp.save()
            info = serializers.serialize('json', Employee.objects.filter(email = request.POST['email']))
            success = True
            return HttpResponse(json.dumps({'success':str(success).lower(), 'info':info}))
        else:
            message = 'Password wrong!'
            return HttpResponse(json.dumps({'success':str(success).lower(), 'message':message}), status = 401)
    except:
        message = 'Email not found!'
        return HttpResponse(json.dumps({'success':str(success).lower(), 'message':message}), status = 401)

如果使用 render_to_response,我只添加 RequestContext 但 HttpResponse,我不知道该怎么做。

我使用 Django 1.4
我的问题在哪里

==========================

当我更改呈现 HTML 的函数时,我的问题得到了解决:

def homepage(request):
    return render_to_response('index.html')

def homepage(request):
    return render_to_response('index.html', context_instance=RequestContext(request))

这是一个愚蠢的错误...谢谢...

4

2 回答 2

2

如果您使用 ajax 发送表单并包含 jQuery,您有两种可能性:

  1. 手动将 csrfmiddlewaretoken 数据添加到您的 POST 请求中
  2. 通过修改 jQuery ajax 请求标头自动化 CSRF 令牌处理

1.手动添加csrfmiddlewaretoken

var data = {
    csrfmiddlewaretoken: $('#myForm input[name=csrfmiddlewaretoken]').val(),
    foo: 'bar',
};

$.ajax({
    type: 'POST',
    url: 'url/to/ajax/',
    data: data,
    dataType: 'json',
    success: function(result, textStatus, jqXHR) {
        // do something with result
    },
});

2. 自动化 CSRF 令牌处理

jQuery(document).ajaxSend(function(event, xhr, settings) {
    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;
    }
    function sameOrigin(url) {
        // url could be relative or scheme relative or absolute
        var host = document.location.host; // host + port
        var protocol = document.location.protocol;
        var sr_origin = '//' + host;
        var origin = protocol + sr_origin;
        // Allow absolute or scheme relative URLs to same origin
        return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
            (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
            // or any other URL that isn't scheme relative or absolute i.e relative.
            !(/^(\/\/|http:|https:).*/.test(url));
    }
    function safeMethod(method) {
        return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
    }

    if (!safeMethod(settings.type) && sameOrigin(settings.url)) {
        xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
    }
});

但是:据说修改ajax请求头是不好的做法。因此,我会选择第一个解决方案。

来源:跨站请求伪造保护:AJAX

于 2012-06-22T09:37:01.307 回答
-3

Django 文档(CSRF DOC LINK)清楚地解释了如何启用它。

这应该是启用 csrf 令牌编写视图的基本方式。

from django.views.decorators.csrf import csrf_protect

@csrf_protect
def form(request):
    if request.method == 'GET':
            #your code
            context = {}
            return render (request, "page.html", context )
于 2012-06-22T09:04:16.953 回答