从 Django 的 CreateView 中的 url 参数设置 ForeignKey 值

Set ForeignKey value from url parameter in Django's CreateView

class Event(models.Model):
  ...

class Question(models.Model):
  event = models.ForeignKey(Event)

我有 url 模式,例如 /events/(?P<event_id>\d+)/question/add/$ 绑定到 QuestionCreateView

QuestionCreateView(CreateView):
    model = Question
    form_class = QuestionForm

    def form_valid(self, form):
        form.instance.event = [???]
        return super(QuestionCreateView, self).form_valid(form)

我想得到什么:

基于 class 的视图是否可行?看起来 DetailViewEvent 以及 CreateViewQuestion 的疯狂组合。

Url 关键字参数在视图中可用 self.kwargs:

from django.shortcuts import get_object_or_404

class QuestionCreateView(CreateView):
    model = Question
    form_class = QuestionForm

    def form_valid(self, form):
        form.instance.event = get_object_or_404(Event,
                                                pk=self.kwargs['event_id'])
        return super(QuestionCreateView, self).form_valid(form)