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

后端 未结 3 2083
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-29 23:14

So I have a model that includes:

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

My view is like so:



        
3条回答
  •  星月不相逢
    2020-11-29 23:54

    I know that this is old, but for other people with this problem:

    There is an even simpler way - since saving a form multiple times will always use the same model instance, you can also do:

    def form_valid(self, form):
        obj = form.save(commit=False)
        obj.created_by = self.request.user
        return super(PlaceFormView, self).form_valid(form)
    

    That way, you get all the benefits of the super call - it's trivial to see that you're really only adding those two lines of code, and you don't have to repeat yourself by replicating the redirect logic.

提交回复
热议问题