Django class-based view - UpdateView - How to access the request user while processing the form?

In a basic UpdateView update in Django, I exclude the user field as it is internal to the system and I will not ask for it. Now, what is the correct way for Django to pass the user to the form. (As I do now, I pass the user to the init form and then override the save () method. But I'm sure there is a right way to do this. Hidden field or things of this nature.

# models.py class Entry(models.Model): user = models.ForeignKey( User, related_name="%(class)s", null=False ) name = models.CharField( blank=False, max_length=58, ) is_active = models.BooleanField(default=False) class Meta: ordering = ['name',] def __unicode__(self): return u'%s' % self.name # forms.py class EntryForm(forms.ModelForm): class Meta: model = Entry exclude = ('user',) # views.py class UpdateEntry(UpdateView): model = Entry form_class = EntryForm template_name = "entry/entry_update.html" success_url = reverse_lazy('entry_update') @method_decorator(login_required) def dispatch(self, *args, **kwargs): return super(UpdateEntry, self).dispatch(*args, **kwargs) # urls.py url(r'^entry/edit/(?P<pk>\d+)/$', UpdateEntry.as_view(), name='entry_update' ), 
+7
source share
2 answers

Hacking involving passing a hidden field does not make sense, since it really has nothing to do with the client - this classic problem of β€œassociate with a registered user” should definitely be performed on the server side.

I would put this behavior in the form_valid method.

 class MyUpdateView(UpdateView): def form_valid(self, form): instance = form.save(commit=False) instance.user = self.request.user super(MyUpdateView, self).save(form) # the default implementation of form_valid is... # def form_valid(self, form): # self.object = form.save() # return HttpResponseRedirect(self.get_success_url()) 
+7
source

Must return an HttpResponse object. Below is the code:

 class MyUpdateView(UpdateView): def form_valid(self, form): instance = form.save(commit=False) instance.user = self.request.user return super(MyUpdateView, self).form_valid(form) 
+2
source

All Articles