E
E
Exzyggwp2020-02-10 18:27:13
Django
Exzyggwp, 2020-02-10 18:27:13

How to merge Forms from different models in Django admin?

Hello! I'm new to django, I'm sorry not to judge strictly, just help a newbie in learning pliz.

I want to create a database for tests (Subjects, questions, answers). 3 models are interconnected. here is the models.py code:

spoiler

from django.db import models

# Модель Предметов

class Subject(models.Model):
  subject_name = models.CharField("Название предмета:", max_length=100)
  LEVEL_CHOICES = ( 
    ("1", "1"),
    ("2", "2"), 
    ("3", "3"), 
) 
  level = models.CharField( 
    "Уровень предмета:",
        max_length = 20, 
        choices = LEVEL_CHOICES, 
        default = '1'
        )

  def __str__(self):
    return self.subject_name

  class Meta:
    verbose_name = "Предмет"
    verbose_name_plural = "Предметы"

# Модель Вопросов

class Question(models.Model):
  subject_id = models.ForeignKey(Subject, verbose_name='Предмет', on_delete=models.CASCADE)
  question = models.TextField("Вопрос")

  def __str__(self):
    return self.question

  class Meta:
    verbose_name = "Вопрос"
    verbose_name_plural = "Вопросы"

# Модель Ответов

class Answer(models.Model):
  question_id = models.ForeignKey(Question, verbose_name='Вопрос', on_delete=models.CASCADE)
  answer = models.TextField("Ответ")
  correct_answer = ( 
    ("0", "Нет"),
    ("1", "Да"),
) 
  level = models.CharField( 
    "Правильный ответ:",
        max_length = 1, 
        choices = correct_answer, 
        default = '0'
        )

  def __str__(self):
    return self.answer

  class Meta:
    verbose_name = "Ответ"
    verbose_name_plural = "Ответы"


admin.py :
spoiler

from django.contrib import admin
from .models import Subject, Question, Answer

admin.site.register(Subject)
admin.site.register(Question)
admin.site.register(Answer)



Here you can see that the models of questions and answers are displayed separately:
spoiler

5e4174da6ca47429751458.png
5e4174e2d0578096476433.png


I need to make sure that when adding a Question , there is also a form for adding answers in one place.
(Making 1 table for questions and answers is not an option, because I need the answers to be in a separate table in order to add additional fields later).

And here another problem arises, how to make the forms for adding answers display 4 pieces, and so that they are added 4 times to the table under different IDs, the foreginkey is the same from the question model.

I didn’t find it in Google or I’m writing something wrong somehow .. In the documentation of this, I personally can’t find it .. Help someone who knows please ..

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
Lyokha, 2020-02-11
@EdFonse

You need to use inlines.
https://docs.djangoproject.com/en/3.0/ref/contrib/...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question