How to set ForeignKey in CreateView?

Vlad T. picture Vlad T. · Apr 30, 2012 · Viewed 19.5k times · Source

I have a model:

class Article(models.Model):
    text = models.CharField()
    author = models.ForeignKey(User)

How do I write class-based view that creates a new model instance and sets author foreign key to request.user?

Update:

Solution moved to separate answer below.

Answer

Vlad T. picture Vlad T. · May 12, 2012

I solved this by overriding form_valid method. Here is verbose style to clarify things:

class CreateArticle(CreateView):
    model = Article

    def form_valid(self, form):
        article = form.save(commit=False)
        article.author = self.request.user
        #article.save()  # This is redundant, see comments.
        return super(CreateArticle, self).form_valid(form)

Yet we can make it short (thanks dowjones123), this case is mentioned in docs.:

class CreateArticle(CreateView):
    model = Article

    def form_valid(self, form):
        form.instance.author = self.request.user
        return super(CreateArticle, self).form_valid(form)