[英]Django auto save the current user in the model on save
I am trying to save the user automatically when saving new data.我试图在保存新数据时自动保存用户。 I mean I want to save the user id for the user who is posting a new thing (submitting a form) without asking that user to choose his account from the droplist (the droplist from the User ForeignKey)
我的意思是我想为发布新事物(提交表单)的用户保存用户 ID,而不要求该用户从下拉列表中选择他的帐户(来自 User ForeignKey 的下拉列表)
Try 1 :尝试 1:
models.py模型.py
class Feedback(models.Model):
.
.
author = models.ForeignKey(
get_user_model(),
on_delete=models.CASCADE,
editable=False,
)
def save(self, *args, **kwargs):
self.author = get_user_model().objects.get(id=2) #############
return super().save(*args, **kwargs)
It's working if I hard-coded the user-id get(id=2)
.如果我对用户 ID
get(id=2)
进行硬编码,它就可以工作。 How can I make the id dynamic?如何使 id 动态化?
Edit:编辑:
Try 2 :尝试 2:
I tried also doing it with the view:我也试过用视图来做:
models.py模型.py
class Feedback(models.Model):
.
.
author = models.ForeignKey(
get_user_model(),
on_delete=models.CASCADE,
editable=False,
null=True
blank=True
)
# without save()
views.py视图.py
class FeedbackForm(ModelForm):
class Meta:
model = Feedback
fields = "__all__"
class FeedbackListView(generics.ListCreateAPIView):
queryset = Feedback.objects.all()
serializer_class = FeedbackSerializer
from_class = FeedbackForm
permission_classes = [FeedbackPermission,] # I also tried AllowAny
def form_valid(self, form, FeedbackForm):
obj = form.save(commit=False) # I also tried self.obj = ...
obj.author = self.request.user # I also tried self.obj.author = ...
obj.save() # I also tried self.obj.save()
return super().form_valid(form)
But on the second try (with forms), the author field remains null.但是在第二次尝试(使用表单)时,作者字段仍然为空。
ListCreateAPIView
don't have method form_valid
, look at this ListCreateAPIView
没有方法form_valid
,看看这个
In your class FeedbackListView
you need to do something like this:在您的
class FeedbackListView
中,您需要执行以下操作:
class FeedbackListView(generics.ListCreateAPIView):
queryset = Feedback.objects.all()
serializer_class = FeedbackSerializer
def perform_create(self, serializer):
# The request user is set as author automatically.
serializer.save(author=self.request.user)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.