Where does Django get the User from in self.request.user?
When executing a GET request, Django sees the User, and when executing a POST request, he does not see it and throws such an error. User information is transmitted in the cookie from the frontend.
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)
Override the perform_create
method of view and pass the user to the serializer for saving.
def perform_create(self, serializer):
serializer.save(user=self.request.user)
The user field should also have a value while creating a new record as it is required.
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.