DRF(django-rest-framework)和TokenAuthentication,如何自动填充基于令牌的json字段?

时间:2016-09-10 10:53:34

标签: android django django-rest-framework token

settings.py

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication',
    ),
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.AllowAny',
    ),
}

serializers.py

class UserSerializer(serializers.ModelSerializer):
    related_postwriter = serializers.PrimaryKeyRelatedField(many=True, read_only=True)
    class Meta:
        model = User
        fields = ('id', 'username', 'email', 'related_postwriter')

class PostSerializer(serializers.ModelSerializer):
    class Meta:
        model = Post
        fields = ('id', 'created_date', 'author', 'text', 'image')
    def create(self, validated_data):
        validated_data['author'] = self.context['request'].user
        return super(PostSerializer, self).create(validated_data)

models.py

class Post(models.Model):
    author = models.ForeignKey(User, related_name='related_postwriter')
    text = models.TextField(blank = False)
    image = models.ImageField(null = False, blank = False, upload_to='images')
    created_date = models.DateTimeField(
        default=timezone.now
        )

    def __str__(self):              # __unicode__ on Python 2
        return self.text

views.py

class PostViewSet(viewsets.ModelViewSet):
    serializer_class = PostSerializer
    permission_classes = [IsAuthenticated]
    queryset = Post.objects.all()

我必须为json请求和json响应创建这个RESTful api。 当我使用这个RESTful api for Android应用程序时,我了解到我登录并从RESTful api获取Token,然后该Token用于通过Header将数据发布到RESTful api。

作为邮差捕获,

enter image description here

我必须填写"作者":"编号"在身体上。我认为这个数字意味着用户在我的RESTful api上注册了订单。从上面捕获,该作者是我的RESTful api的第一个用户。

如果我将作者字段设为空,则返回

{
  "author": [
    "This field is required."
  ]
}
  1. 我如何填写"作者"部分自动使用令牌(或其他方式不使用令牌)?

  2. 如何获取json响应"author":"some alphabet name readable",而不是"author":"1 or 2 like number"作为捕获。我希望表格像"author":"stackoverflowman"

1 个答案:

答案 0 :(得分:2)

对于您的第一个问题,您应该添加PostViewSet此功能:

def perform_create(self, serializer):
     serializer.save(author=self.request.user)

对于您的第二个问题,您应该从UserSerializer致电PostSerializer

class PostSerializer(serializers.ModelSerializer):
    author = UserSerializer(read_only=True)

    class Meta:
        model = Post
        fields = ('id', 'created_date', 'author', 'text', 'image')

修改

如果您只想要一个字段,则可以使用source声明一个字段:

class PostSerializer(serializers.ModelSerializer):
    author = serializers.ReadOnlyField(source='author.username')

    class Meta:
        model = Post
        fields = ('id', 'created_date', 'author', 'text', 'image')