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)
Try 1 :
models.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)
. How can I make the id dynamic?
Edit:
Try 2 :
I tried also doing it with the view:
models.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
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.
CodePudding user response:
ListCreateAPIView
don't have method form_valid
, look at this
In your class FeedbackListView
you need to do something like this:
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)