Reputation: 29
I have the following where a comment is posted via a POST request
urlpatterns = [
path("recipes/comments/", RecipeCommentView.as_view(), name="post_comment"), # POST
]
Views.py
@permission_classes([AllowAny])
class RecipeCommentView(generics.CreateAPIView):
queryset = models.RecipeComment.objects.all()
serializer_class = RecipeCommentSerializer
Serializers.py
class UserSerialiser(serializers.ModelSerializer):
class Meta:
model = models.User
fields = ["username"]
class RecipeCommentSerializer(serializers.ModelSerializer):
published_by = UserSerialiser(read_only=True)
class Meta:
model = models.PublishedRecipeComment
fields = ["recipe", "published_by", "content", "created_at"]
ordering = ["position"]
Models.py
class RecipeComment(models.Model):
recipe = models.ForeignKey(Recipe, on_delete=models.PROTECT, related_name="comments")
published_by = models.ForeignKey(User, on_delete=models.PROTECT, null=True)
content = models.CharField(max_length=2500)
created_at = models.DateTimeField(auto_now_add=True)
I am using the User model from django.contrib.auth.models, how can I have the username of the currently logged in user attached to the published_by field?
When I go to check the recently added comment that i have POSTed, the username does not show, it shows me null:
{
"recipe": 1,
"published_by": null,
"content": "this is a comment",
"created_at": "2021-07-24T12:13:10.391236Z"
}
I'm looking to populate the published_by field with the username of the user that has posted it.
Upvotes: 0
Views: 100
Reputation:
It must be work well, i tested it:
class RecipeCommentSerializer(serializers.ModelSerializer):
published_by = UserSerialiser(read_only=True)
class Meta:
model = models.PublishedRecipeComment
fields = ["recipe", "published_by", "content", "created_at"]
ordering = ["position"]
def create(self, validated_data):
request = self.context['request']
ModelClass = self.Meta.model
instance = ModelClass.objects.create(
**validated_data,
**{
'published_by': request.user
}
)
return instance
Upvotes: 2