I have the following code working perfectly. I can create a Post
object from DRF panel by selecting an image and a user. However I want DRF to populate the user field by the currently logged in user.
models.py
class Post(TimeStamped): user = models.ForeignKey(User) photo = models.ImageField(upload_to='upload/') hidden = models.BooleanField(default=False) upvotes = models.PositiveIntegerField(default=0) downvotes = models.PositiveIntegerField(default=0) comments = models.PositiveIntegerField(default=0)
serializers.py
class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = ['id', 'user', 'photo']
views.py
class PhotoListAPIView(generics.ListCreateAPIView): queryset = Post.objects.filter(hidden=False) serializer_class = PostSerializer authentication_classes = (SessionAuthentication, BasicAuthentication) permission_classes = (IsAuthenticated,)
How can I do this?
Open auth/urls.py and add update profile endpoint. we should send a PUT request to API for checking update profile endpoint. We must add username, first_name, last_name and email. If fields passed validations, user profile will be changed.
The HyperlinkedModelSerializer class is similar to the ModelSerializer class except that it uses hyperlinks to represent relationships, rather than primary keys. By default the serializer will include a url field instead of a primary key field.
Off the top of my head, you can just override the perform_create()
method:
class PhotoListAPIView(generics.ListCreateAPIView): ... def perform_create(self, serializer): serializer.save(user=self.request.user)
Give that a shot and let me know if it works
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With