Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing request.user in class based generic view CreateView in order to set FK field in Django

So I have a model that includes:

class Place(models.Model):     ....     created_by = models.ForeignKey(User) 

My view is like so:

class PlaceFormView(CreateView):     form_class = PlaceForm      @method_decorator(login_required)     def dispatch(self, *args, **kwargs):         return super(PlaceFormView, self).dispatch(*args, **kwargs) 

Is there a way for me to access request.user and set created_by to that user? I've looked through the docs, but can't seem to find any hints toward this.

`

like image 901
Brian Avatar asked Apr 26 '11 03:04

Brian


People also ask

What are generic views in Django?

Unlike classic views, generic views are classes not functions. Django offers a set of classes for generic views in django. views. generic, and every generic view is one of those classes or a class that inherits from one of them.

What is Form_class in Django?

Hi Christopher 'form_class' is used in Django Class Based to depict the Form to be used in a class based view. See example in the docs: https://docs.djangoproject.com/en/2.1/topics/class-based-views/generic-editing/

Why use Django generic views?

Django's generic views were developed to ease that pain. They take certain common idioms and patterns found in view development and abstract them so that you can quickly write common views of data without having to write too much code.


1 Answers

How about overriding form_valid which does the form saving? Save it yourself, do whatever you want to it, then do the redirect.

class PlaceFormView(CreateView):     form_class = PlaceForm      @method_decorator(login_required)     def dispatch(self, *args, **kwargs):         return super(PlaceFormView, self).dispatch(*args, **kwargs)      def form_valid(self, form):         obj = form.save(commit=False)         obj.created_by = self.request.user         obj.save()                 return http.HttpResponseRedirect(self.get_success_url()) 
like image 194
Yuji 'Tomita' Tomita Avatar answered Nov 11 '22 16:11

Yuji 'Tomita' Tomita