There are answers that are mainly related to the User
model foreign key. However, let's suppose a simple scenario in which there is a model Comment
containing a foreign key of the Article
model, and you need to have a CreateView
for Comment
where each comment will have a foreign key of the Article
model. In that case, the Article
id would probably be in the URL
, for example, /article/<article-id>/comment/create/
. Here is how you can deal with such a scenario
class CommentCreateView(CreateView):
model = Comment
# template_name, etc
def dispatch(self, request, *args, **kwargs):
self.article = get_object_or_404(Article, pk=self.kwargs['article_id'])
return super(CommentCreateView, self).dispatch(request, *args, **kwargs)
def form_valid(self, form):
form.instance.article= self.article # if the article is not a required field, otherwise you can use the commit=False way
return super(CommentCreateView, self).form_valid(form)