在Django中用新对象创建关联记录

时间:2018-03-17 17:37:39

标签: django

我正在使用Django 2

我有两个型号

class Chapter(models.Model):
    name = models.CharField(max_length=250, blank=False)

    def __str__(self):
        return self.name


class ChapterQuestion(models.Model):
    chapter = models.ForeignKey(Chapter, on_delete=models.CASCADE)
    word = models.CharField(max_length=250)
    definition = models.CharField(max_length=250)

    def __str__(self):
        return self.word

我希望在创建questions时能够添加多个chapter。 所有这些都将仅使用单一表格完成。

到目前为止我写的视图是

class NewChapter(CreateView):
    template_name = 'courses/chapter/new_chapter.html'
    model = Chapter
    fields = ['name']

    def get_context_data(self, **kwargs):
        context = super(NewChapter, self).get_context_data(**kwargs)
        course = Course.objects.get(pk=self.kwargs['course_id'])
        if course is None:
            messages.error(self.request, 'Course not found')
            return reverse('course:list')
        context['course'] = course

        return context

    def form_valid(self, form):
        form.instance.created_by = self.request.user
        form.instance.course = Course.objects.get(pk=self.kwargs['course_id'])
        form.save()

        return super().form_valid(form)

    def get_success_url(self):
        return reverse('course:detail', self.kwargs['course_id'])

但无法理解如何开始。任何指南或教程都会很明显。

1 个答案:

答案 0 :(得分:0)

我不认为CreateView支持表单集,因此您必须使用基于常规类的视图或功能视图。

ChapterQuestion模型创建表单类时,请记住exclude外键字段chapter

然后,创建您的formset。 Documentation将指导您完成此操作。

现在,在您看来,您可以这样做:

# assuming you'll use a regular class based view

def post(self, request):
    form = ChapterForm(request.POST)
    formset = ChapterQuestionFormset(request.POST)

    if form.is_valid() and formset.is_valid():
        chapter = form.save() # first, save the chapter

        for f in formset: # loop through all the forms in formset
            question = f.save(commit=False)
            question.chapter = chapter # set the chapter
            question.save() # save the question to db

        return redirect('success')