首页 > 解决方案 > How to create multiple models from the same form in Django

问题描述

I have a create view used to make a quiz that has the title, author, etc but my quizzes are made up of answer models that are linked to question models that are then linked to this quiz. How do I make a form for creating a whole quiz, including the questions and correct answers, from this?

class QuizCreateView(LoginRequiredMixin, CreateView):
    model = Quiz
    fields = ['title', 'video_link', 'question_amount']

def form_valid(self, form):
    form.instance.author = self.request.user
    return super().form_valid(form)

I use crispy forms in the template

{% extends "quiz_app/base.html" %}
{% load crispy_forms_tags %}
{% block content %}
    <div class="content-section">
        <form method="POST">
            {% csrf_token %}
            <fieldset class="form-group">
                <legend class="border-bottom mb-4">Create Quiz</legend>
                {{ form|crispy }}
            </fieldset>
            <div class="form-group">
                <button class="btn btn-blue" type="submit">Submit</button>
            </div>
        </form>
    </div>
{% endblock content %}

TIA

标签: djangoformsdjango-modelsdjango-class-based-viewsdjango-crispy-forms

解决方案


您可以使用Inlines,它允许您将模型的表单嵌入到父模型的表单中,例如,在您的测验表单中,您可以有多个问题表单。

不幸的是,这只适用于 2 个级别,您需要第三个级别的答案,您有两种选择:

  • 您可以创建两种不同的表单:包含多个问题表单的测验表单和包含多个答案表单的问题表单;
  • 您可以使用django-nested-admin它允许您拥有多个嵌套表单。

这是一个关于 django-nested-admin的简短教程,该示例反映了您的需要。


推荐阅读