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/
,则Event
获取event_id
个实例,并在保存之前填充我的新Question
个实例是否可以使用基于类的视图?对DetailView
Event
CreateView
和Question
{{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)