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

时间:2017-07-19 12:41:05

标签: python ajax django django-rest-framework

我正在尝试将json数据发送到我的网站上的django后端。当我想在view函数中获取用户对象时,我得到了这个“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)

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

1 个答案:

答案 0 :(得分:3)

在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,因为您已经在做。