DJANGO:在创建视图中自动添加相应的外键值

时间:2018-08-10 16:27:00

标签: django django-models django-forms django-templates django-views

我正在使用以下模型创建CreateView

from django.db import models
from uuid import uuid4
from django.core.validators import MinValueValidator,MaxValueValidator
from questions.models import Question
from django.urls import reverse

class ExamPaper(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid4)
    name = models.CharField(max_length=300)
    for_class = models.PositiveSmallIntegerField(
        validators=(
            MinValueValidator(1),
            MaxValueValidator(12),
        ))
    date = models.DateField(null=True, blank=True)

    PARTS = (
        ("A", "A"),
        ("B", "B"),
        ("C", "C"),
        ("D", "D"),
        ("E", "E"),
    )
    part = models.CharField(
        max_length=1, choices=PARTS, null=True,blank=True)

    def __str__(self):
        return f"{self.name} ({self.get_part_display()})"

    def get_absolute_url(self):
        return reverse("exam_detail", args=[str(self.pk)])

class ExamQuestions(models.Model):
    exam = models.ForeignKey(
        ExamPaper, on_delete=models.SET_NULL, null=True, 
        related_name="examquestions")
    question = models.ForeignKey(
        Question, on_delete=models.CASCADE,)
    marks = models.PositiveSmallIntegerField(
        validators=(MaxValueValidator(20), ))

    def __str__(self):
        return self.question.question[:150]

    def get_absolute_url(self):
        return reverse("exam_detail", args=[str(self.exam.pk)])

我正在尝试使用CreateView制作表单,在其中可以向ExamPaper添加问题和标记。我已经使用CreatView模型创建了一个ExamPaper,并在其中添加了一个链接以添加问题。

我想要的是,每当我添加问题时,就会将考试字段分配给该问题。

views.py

class ExamCreateView(CreateView):
    model = ExamPaper
    template_name = "exam_new.html"
    fields = "__all__"

class ExamQuestionsView(CreateView):
    model = ExamQuestions
    fields = "question", "marks",
    template_name = "exam_ques_new.html"

我能够同时获得两者的表格,但是在ExamQuestionView中,我必须从整个列表中选择考试。

0 个答案:

没有答案