[英]How can I get a username from django User Model
I have the following where a comment is posted via a POST request我有以下内容,其中通过 POST 请求发表评论
urlpatterns = [
path("recipes/comments/", RecipeCommentView.as_view(), name="post_comment"), # POST
]
Views.py视图.py
@permission_classes([AllowAny])
class RecipeCommentView(generics.CreateAPIView):
queryset = models.RecipeComment.objects.all()
serializer_class = RecipeCommentSerializer
Serializers.py序列化器.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模型.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?我正在使用 django.contrib.auth.models 中的用户模型,如何将当前登录用户的用户名附加到published_by 字段?
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.我希望用发布它的用户的用户名填充published_by 字段。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.