【问题标题】:How to add current user data when saving in django model在 django 模型中保存时如何添加当前用户数据
【发布时间】:2015-08-16 04:09:13
【问题描述】:

我正在创建小型 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)

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

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

    • rest_framework.authentication.SessionAuthenticationrest_framework.authentication.TokenAuthentication 在项目中使用。如何通过请求传递当前用户数据?
    • 如果您使用rest_framework.authentication.TokenAuthentication,那么在登录用户时,您应该为用户创建一个访问令牌并将其提供给客户端作为对登录请求的响应。在后续请求中,此令牌应包含在 Authorization 请求标头中。
    • 您可以点击此链接,它包含有关所有可用于 REST 框架的身份验证方案的信息。 django-rest-framework.org/api-guide/authentication
    猜你喜欢
    • 1970-01-01
    • 2020-04-30
    • 2012-06-15
    • 2014-08-15
    • 1970-01-01
    • 2021-06-08
    • 2021-02-02
    • 2012-03-19
    相关资源
    最近更新 更多