Django Rest Framework - 用户字段不能为空

时间:2017-05-25 19:41:40

标签: django django-rest-framework

我正在学习Django和Django Rest Framework来创建一个API,并且无法解释为什么当我运行这个命令时:

sqlplus 'USER/PASSWORD@(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=DB_HOST)(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=SERVICE_NAME_YOU_USE_IN_SQLDEVELOPER)))' 

我收到一条错误消息:

http --json POST http://127.0.0.1:8000/api/v1/stocks/ book_code='Abook' 'Authorization: Token 123243434354353'

'用户'字段是必需的,但我希望它能够根据我提供的令牌填充用户,即经过身份验证的用户。

这是HTTP/1.0 400 Bad Request Allow: GET, POST, HEAD, OPTIONS Content-Type: application/json Date: Thu, 25 May 2017 19:16:37 GMT Server: WSGIServer/0.2 CPython/3.6.0 Vary: Accept X-Frame-Options: SAMEORIGIN { "user": [ "This field is required." ]}

bookstock/models.py

这是from django.db import models from django.contrib.auth.models import User class Stock(models.Model): ''' Model representing the stock info. ''' user = models.ForeignKey(User) book_code = models.CharField(max_length=14, null=True, blank=True) def __str__(self): return self.book_code

api/serializer.py

这是from bookstock.models import Stock from rest_framework import serializers class StockSerializer(serializers.ModelSerializer): class Meta: model = Stock fields = ('id', 'user', 'book_code')

api/views.py

这是from rest_framework import generics from bookstock.models import Stock from api.serializers import StockSerializer from rest_framework.permissions import IsAuthenticated class StockList(generics.ListCreateAPIView): serializer_class = StockSerializer permission_classes = (IsAuthenticated,) def get_queryset(self): user = self.request.user return Stock.objects.filter(user=user) def perform_create(self, serializer): serializer.save(user=self.request.user, ) def perform_update(self, serializer): serializer.save(user=self.request.user)

api/urls.py

我错过了什么?根据来自SO的答案,from django.conf.urls import url, include from api import views from rest_framework.authtoken.views import obtain_auth_token urlpatterns = [ url(r'^v1/stocks/$', views.StockList.as_view()), url(r'^v1/api-token-auth/', obtain_auth_token), url(r'v1/api-auth/', include('rest_framework.urls', namespace='rest_framework')), ] perform_create覆盖应填充用户权限吗?

1 个答案:

答案 0 :(得分:0)

在序列化程序验证后,您的perform_create方法会调用create方法。在此阶段,DRF将找到并标记缺少的用户字段:https://github.com/encode/django-rest-framework/blob/master/rest_framework/mixins.py#L14

有多种方法,即将序列化器字段设置为read_only=True或覆盖序列化器上的validate_user方法。

我认为最优雅的方式是使用DRF' currentuserdefault验证器:http://www.django-rest-framework.org/api-guide/validators/#currentuserdefault

user = serializers.HiddenField(default=serializers.CurrentUserDefault())

(将HiddenField替换为CharField或您喜欢的任何内容)