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
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
to Django users
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. 

Simon Connah

unread,
Apr 4, 2018, 9:51:33 PM4/4/18
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.
--
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...@googlegroups.com.
To post to this group, send email to django...@googlegroups.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.
Reply all
Reply to author
Forward
0 new messages