2017-05-25 74 views
0

我學習Django和Django的REST框架來創建一個API,爲什麼當我運行此命令不能換我周圍的頭:Django的REST框架 - 用戶字段不能爲空

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

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')), 

] 

我錯過了什麼?根據SO的回答,perform_createperform_update重寫應該填充用戶權限?

回答

0

perform_create方法由您的View的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()) 

(與CharField或任何你喜歡更換HiddenField

+0

非常感謝!這解決了問題! – shaz