django - 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
解决方案
您可以使用Inlines,它允许您将模型的表单嵌入到父模型的表单中,例如,在您的测验表单中,您可以有多个问题表单。
不幸的是,这只适用于 2 个级别,您需要第三个级别的答案,您有两种选择:
- 您可以创建两种不同的表单:包含多个问题表单的测验表单和包含多个答案表单的问题表单;
- 您可以使用django-nested-admin它允许您拥有多个嵌套表单。
这是一个关于 django-nested-admin的简短教程,该示例反映了您的需要。
推荐阅读
- elasticsearch - 为什么 searchResult.TotalHits() 与 len(searchResult.Hits.Hits) 不同?
- java - 从不同的片段访问列表
- pandas - 如何在熊猫列上计算非空值然后聚合
- c# - TFS (AzureDevOps) 2015 C# 获取构建中使用的变量
- node.js - 将 S3 存储桶的内容复制到另一个存储桶 | 节点JS
- angular - 如何在点击时打开弹出窗口?
- c# - 我想在数据表中添加新行而不对现有数据产生任何影响
- string - 如果列表中包含特定单词,如何从列表中删除字符串
- c++11 - 用于 constexpr 深度和 IEEE 754 指数计算的 NVIDIA nvcc 编译标志
- c# - 无法创建 X 类型的常量值