In my project I have the Post and Category Model and full working JWT Authentication.
class Category(models.Model):
name = models.CharField(max_length=255)
def __str__(self):
return self.name
class Post(models.Model):
title = models.CharField(max_length=50)
content = models.TextField()
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
author = models.ForeignKey(User, on_delete=models.CASCADE)
category = models.ManyToManyField(Category, related_name='posts')
class Category(models.Model):
name = models.CharField(max_length=255)
def __str__(self):
return self.name
I want to create a view, that creates a new Post object, in which author will be assigned to Token owner that I pass in authorization (Bearer Token ) postman.image.example. I dont know how to do it please help. Sorry for my english.
Serializer
class PostSerializer(FlexFieldsModelSerializer):
class Meta:
model = Post
fields = '__all__'
read_only_fields = ['id', 'created']
expandable_fields = {
'category': ('blog.CategorySerializer', {'many': True}),
'comments': ('blog.CommentSerializer', {'many': True}),
'images': ('blog.ImageSerializer', {'many': True}),
}
Advertisement
Answer
From what I understand, you want to automatically associate the request.user as the author of the post (s)he creates. Whether your auth is JWT-based or session-based does not influenced that (as long as it is set up correctly).
For this you need to pass the request object to your serializer, here is the trick:
# serializers.py
class PostSerializer(FlexFieldsModelSerializer):
class Meta:
model = Post
fields = '__all__'
read_only_fields = ['id', 'created', 'author'] # set author as read-only field
expandable_fields = {
'category': ('blog.CategorySerializer', {'many': True}),
'comments': ('blog.CommentSerializer', {'many': True}),
'images': ('blog.ImageSerializer', {'many': True}),
}
def create(self, validated_data):
# here you get the user from the request
user = self.context['request'].user
return Post.objects.create(author=user, **validated_data)
# views.py
from .models import Post
from .serializers import PostSerializer
from rest_framework import generics
from rest_framework.permissions import IsAuthenticated
class PostCreate(generics.CreateAPIView):
queryset=Post.objects.all()
serializer_class = PostSerializer
permission_classes = [IsAuthenticated]
def get_serializer_context(self):
# this is the trick since you want to pass the request object to your serializer
context = super().get_serializer_context()
context.update({"request": self.request})
return context