{ "user" :[ "This field is required." ]} in Django REST Framework



Django从哪里获得self.request.user中的User ?

当执行一个GET请求时,Django会看到User,而当执行一个POST请求时,Django看不到User并抛出这样一个错误。用户信息通过cookie从前端传输。

views.py

from rest_framework import generics
from rest_framework.permissions import IsAuthenticated
from rest_framework import pagination
from rest_framework.response import Response
from api.models.notes import Notes
from api.serializers.notes import NotesSerializer
class FilterNotes(generics.ListCreateAPIView):
serializer_class = NotesSerializer
permission_classes = (IsAuthenticated,)
def get_queryset(self):
return Notes.objects 
.filter(user=self.request.user.id) 
.order_by('-time')

models.py

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

class Notes(models.Model):
note_id = models.AutoField(primary_key=True)
user = models.ForeignKey(User, models.CASCADE, db_column='user')
time = models.DateTimeField(auto_now_add=True)
message = models.TextField(max_length=50, blank=True, null=True)

重写视图的perform_create方法,并将用户传递给序列化器保存。

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

user字段在需要创建新记录时也应该有一个值。

class FilterNotes(generics.ListCreateAPIView):
serializer_class = NotesSerializer
permission_classes = (IsAuthenticated,)
def get_queryset(self):
queryset = Notes.objects.filter(user=self.request.user)
.order_by('-time')
return queryset

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

相关内容

  • 没有找到相关文章

最新更新