On Tuesday, 3 April 2018 22:17:34 UTC+1, Simon Connah wrote: > > Hi, > > Apologies as this is a newbie question. > > I have a Model, a CBV CreateView and a ModelForm. > > The ModelForm is set to use the model, and the model has a field called > author which is a ForeignKey to default Django auth User model. > > I have removed the author field from the ModelForm as if I allow it the > form widget shows a list of all of the registered users on the website. > > What I need to do is pre-populate the ModelForm with self.request.user > from the CreateView. I've tried doing it in the form_valid() method but > can't seem to get it working. As soon as a user creates an instance of the > Model, I want the author to always equal self.request.user. > > I have a feeling you filter the ModelForm only to show the logged in user > but I'm a bit stuck on that front. Perhaps you have to pre-populate the > field in the ModelForm and then use a HiddenInput for the author field in > the ModelForm? > > Any help would be appreciated. > > Thank you. >
No, the right approach is to do it in form_valid as you tried initially. This is explicitly documented: https://docs.djangoproject.com/en/2.0/topics/class-based-views/generic-editing/#models-and-request-user If you're having trouble, you need to be more specific than "I can't get it working". -- DR. -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to email@example.com. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/4bcfdc2c-7e2f-42dd-9295-1a31d85317d5%40googlegroups.com. For more options, visit https://groups.google.com/d/optout.