在django模型中保存时如何添加当前用户数据

时间:2015-06-02 11:29:25

标签: angularjs django django-models django-views django-rest-framework

我正在创建小型Django / AngularJS应用。用户可以创建帐户,查看所有创建的帖子并添加自己的帖子。

当前版本的应用程序位于:GitHub

模特:models.py

from django.db import models
from django.contrib.auth.models import User

from datetime import datetime

# Post model
class Post(models.Model):
    date = models.DateTimeField(default=datetime.now)
    text = models.CharField(max_length=250)
    author = models.ForeignKey(User)

观点:views.py

from django.shortcuts import render
from rest_framework import generics, permissions

from serializers import UserSerializer, PostSerializer
from django.contrib.auth.models import User
from models import Post
from permissions import PostAuthorCanEditPermission

...

class PostMixin(object):
    queryset = Post.objects.all()
    serializer_class = PostSerializer
    permission_classes = [
        PostAuthorCanEditPermission
    ]

    def pre_save(self, obj):
        """Force author to the current user on save"""
        obj.author = self.request.user
        return super(PostMixin, self).pre_save(obj)


class PostList(PostMixin, generics.ListCreateAPIView):
    pass


class PostDetail(PostMixin, generics.RetrieveUpdateDestroyAPIView):
    pass

...

序列化程序:serializers.py

from rest_framework import serializers
from django.contrib.auth.models import User
from models import Post


class UserSerializer(serializers.ModelSerializer):
    posts = serializers.HyperlinkedIdentityField(view_name='userpost-list', lookup_field='username')

    class Meta:
        model = User
        fields = ('id', 'username', 'first_name', 'last_name', 'posts', )


class PostSerializer(serializers.ModelSerializer):
    author = UserSerializer(required=False)

    def get_validation_exclusions(self, *args, **kwargs):
        # Need to exclude `user` since we'll add that later based off the request
        exclusions = super(PostSerializer, self).get_validation_exclusions(*args, **kwargs)
        return exclusions + ['author']

    class Meta:
        model = Post

但是,当我创建请求(main.js)以向此类添加新帖子时:

var formPostData = {text: $scope.post_text};
$http({
  method: 'POST',
  url: '/api/posts',
  data: formPostData,
  headers: {'Content-Type': 'application/json'}
})

它会引发错误:

Request Method: POST
Request URL:    http://127.0.0.1:8000/api/posts
Django Version: 1.7.6
Exception Type: IntegrityError
Exception Value:    
NOT NULL constraint failed: nucleo_post.author_id

我想,这段代码在保存之前将作者添加到帖子模型中。但它现在无法正常工作。

def pre_save(self, obj):
    """Force author to the current user on save"""
    obj.author = self.request.user
    return super(PostMixin, self).pre_save(obj)

所以我需要一些帮助...

1 个答案:

答案 0 :(得分:1)

这是因为请求没有用户信息。要使request.user起作用,请求应包含授权相关信息。包含此信息取决于您使用的授权机制。如果您使用基于令牌或会话的身份验证,则令牌或会话密钥应该是请求标头或查询参数的一部分(取决于服务器实现)。如果您使用的是rest_framework的登录视图,那么您应该传递用户名:密码以及请求。