Vlad T. Vlad T. - 2 years ago 87
Python Question

How to set ForeignKey in CreateView?

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
foreign key to

Answer Source

I solved this by overriding form_valid method:

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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download