使用django时如何在ajax调用中传递request.user?

Posted

技术标签:

【中文标题】使用django时如何在ajax调用中传递request.user?【英文标题】:How to pass request.user in ajax call when using django? 【发布时间】:2017-12-24 17:57:28 【问题描述】:

我正在尝试将 json 数据发送到我网站上的 django 后端。当我想在视图函数中获取用户对象时,我收到了这个“AnonymousUser”错误。 以下是我的代码:

我的 api 视图:

@api_view(['GET','POST'])
def add_vote(request):
    if request.method =='POST':

        #I think this is where I can't figure out a way to deal with
        user = request.user

        serializer = VoteSerializer(data=request.data)
        if serializer.is_valid():
            instance = serializer.save(creator=user)
            return redirect(instance)
        return Response(serializer.errors)
    if request.method == 'GET':
        votes = VoteTitle.objects.all()
        serializer = VoteSerializer(votes,many=True)
        print(request.user)
        return Response(serializer.data)

这是我的发送函数(一个反应类函数):

sent_json() 
    let send_json = 
        title: this.state.title,
        subjects: [],
    ;
    send_json.subjects = this.state.subjects.map((object) => (
        name: object
    ));
    send_json = JSON.stringify(send_json);
    console.log(send_json);
    let csrftoken = Cookies.get('csrftoken');
    console.log(csrftoken);

    let header = 
        "method": 'POST',
        "body": send_json,
        "headers": 
            "X-CSRFToken": csrftoken,
            "Accept": "application/json",
            "Content-Type": "application/json",
        
    ;
    fetch('http://127.0.0.1:8000/voteapp/add/', header).then(function(response) 
        console.log(response);
        return response.json();
    ).then(function(response) 
        console.log(response);
    ).catch(function(error) 
        alert(error);
    );

django 后端显示的错误消息:

Internal Server Error: /voteapp/add/
Traceback (most recent call last):
  File "/Users/phil/Desktop/Web-Development/mini-blog/env/lib/python3.5/site-packages/django/core/handlers/exception.py", line 42, in inner
    response = get_response(request)
  File "/Users/phil/Desktop/Web-Development/mini-blog/env/lib/python3.5/site-packages/django/core/handlers/base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/Users/phil/Desktop/Web-Development/mini-blog/env/lib/python3.5/site-packages/django/core/handlers/base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Users/phil/Desktop/Web-Development/mini-blog/env/lib/python3.5/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
    return view_func(*args, **kwargs)
  File "/Users/phil/Desktop/Web-Development/mini-blog/env/lib/python3.5/site-packages/django/views/generic/base.py", line 68, in view
    return self.dispatch(request, *args, **kwargs)
  File "/Users/phil/Desktop/Web-Development/mini-blog/env/lib/python3.5/site-packages/rest_framework/views.py", line 489, in dispatch
    response = self.handle_exception(exc)
  File "/Users/phil/Desktop/Web-Development/mini-blog/env/lib/python3.5/site-packages/rest_framework/views.py", line 449, in handle_exception
    self.raise_uncaught_exception(exc)
  File "/Users/phil/Desktop/Web-Development/mini-blog/env/lib/python3.5/site-packages/rest_framework/views.py", line 486, in dispatch
    response = handler(request, *args, **kwargs)
  File "/Users/phil/Desktop/Web-Development/mini-blog/env/lib/python3.5/site-packages/rest_framework/decorators.py", line 52, in handler
    return func(*args, **kwargs)
  File "/Users/phil/Desktop/Web-Development/mini-blog/blog/voteapp/views.py", line 19, in add_vote
    instance = serializer.save(creator=user)
  File "/Users/phil/Desktop/Web-Development/mini-blog/env/lib/python3.5/site-packages/rest_framework/serializers.py", line 215, in save
    self.instance = self.create(validated_data)
  File "/Users/phil/Desktop/Web-Development/mini-blog/blog/voteapp/serializers.py", line 17, in create
    vote = VoteTitle.objects.create(**data)
  File "/Users/phil/Desktop/Web-Development/mini-blog/env/lib/python3.5/site-packages/django/db/models/manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/Users/phil/Desktop/Web-Development/mini-blog/env/lib/python3.5/site-packages/django/db/models/query.py", line 397, in create
    obj = self.model(**kwargs)
  File "/Users/phil/Desktop/Web-Development/mini-blog/env/lib/python3.5/site-packages/django/db/models/base.py", line 537, in __init__
    setattr(self, field.name, rel_obj)
  File "/Users/phil/Desktop/Web-Development/mini-blog/env/lib/python3.5/site-packages/django/db/models/fields/related_descriptors.py", line 211, in __set__
    self.field.remote_field.model._meta.object_name,
ValueError: Cannot assign "<django.contrib.auth.models.AnonymousUser object at 0x1045995f8>": "VoteTitle.creator" must be a "User" instance.

提示错误消息:

SyntaxError (DOM Exception 12): The string did not match the expected pattern.

浏览器中的错误信息:

Failed to load resource: the server responded with a status of 500 (Internal Server Error)

我确定我已经登录了,所以我一定错过了什么。

【问题讨论】:

您能否在代码中使用console.log(csrftoken); 这一行打印 csrf 令牌。当您执行获取请求时会发生什么 yeah csrftoken 打印成功。我最近会在问题中添加响应对象。 如果在request.user下的视图函数中打印用户呢? @hansTheFranz 我得到了“AnonymousUser”。 【参考方案1】:

在您的 javascript 中,使用 fetch 时包含凭据:

let header = 
  "method":'POST',
  "body": send_json,
  "credentials": 'include',
  "headers":
  "X-CSRFToken": csrftoken,
  "Accept": "application/json",
  "Content-Type": "application/json",
  
;

在 Django 视图中,您应该使用request.user,就像您已经在使用的那样。

【讨论】:

是的,这行得通。请问为什么我仍然收到此错误消息“SyntaxError (DOM Exception 12): The string does not match the expected pattern.”发帖成功后 抱歉,我的 Python/Django 比我的 JavaScript 好得多,所以我无能为力。

以上是关于使用django时如何在ajax调用中传递request.user?的主要内容,如果未能解决你的问题,请参考以下文章

通过jQuery ajax调用将值列表传递给django视图

使用 Ajax、Django 将上下文传递到模板中

如何在 django 中通过 AJAX 请求传递数据?

使用 Django 实现 ajax 表单

单击表单复选框并传递复选框布尔值时如何在Django中刷新view.py?

使用 Ajax 方法将变量传递给 python