Creating a model instance using currently logged in user
23 views
Skip to first unread message
Simon Connah
unread,
Apr 3, 2018, 5:17:34 PM4/3/18
Reply to author
Sign in to reply to author
Forward
Sign in to forward
Delete
You do not have permission to delete messages in this group
Copy link
Report message
Sign in to report message
Show original message
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message
to django...@googlegroups.com
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.
Daniel Roseman
unread,
Apr 4, 2018, 2:16:23 PM4/4/18
Reply to author
Sign in to reply to author
Forward
Sign in to forward
Delete
You do not have permission to delete messages in this group
Copy link
Report message
Sign in to report message
Show original message
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message
If you're having trouble, you need to be more specific than "I can't get it working".
--
DR.
Simon Connah
unread,
Apr 4, 2018, 9:51:33 PM4/4/18
Reply to author
Sign in to reply to author
Forward
Sign in to forward
Delete
You do not have permission to delete messages in this group
Copy link
Report message
Sign in to report message
Show original message
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message
to Django users
Hi,
Sorry. When I wrote that message I wasn't thinking properly. After a sleep and a bit of Googling, I sorted the issue out. In the future, I'll be much more explicit about my problems. Just goes to show how important sleep is when programming :).
Thank you for your response though. At least it has confirmed to me that form_valid() is the correct location for things like this.
I seem to have a tendency to miss important details in the Django documentation for some reason.