在Django的CreateView中从url参数设置外键值

时间:2015-01-27 04:19:42

标签: django dry django-class-based-views

class Event(models.Model):
  ...

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

我的网址格式如/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)

我想得到什么:

    如果用户请求event_id 之类的无效/events/9999999/objects/add/,则
  • 会抛出404错误
  • 从网址Event获取event_id个实例,并在保存之前填充我的新Question个实例
  • 以干燥的方式做,因为我有一些其他模型有这样的关系

是否可以使用基于类的视图?对DetailView Event CreateViewQuestion {{1}}来说,它看起来像是一些疯狂的混合。

1 个答案:

答案 0 :(得分:3)

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)