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

Brian picture Brian · Apr 26, 2011 · Viewed 21.2k times · Source

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.

`

Answer

Yuji 'Tomita' Tomita picture Yuji 'Tomita' Tomita · Apr 26, 2011

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())