django创建带有动态创建相关字段的modelform并显示更新的表单字段

时间:2019-05-01 21:40:40

标签: django django-forms modelform

我有以下两个Model类。

class Question(models.Model):
    question_text = models.CharField(max_length = 100)
    pub_date = models.DateTimeField('date published')
    question_type = models.CharField(max_length = 100)
    def __str__(self):
        return self.question_text

class Choice(models.Model):
    choice_text = models.CharField(max_length = 200)
    votes = models.IntegerField(default = 0)
    question = models.ForeignKey(Question, on_delete = models.CASCADE,related_name = 'q_choice')

    def __str__(self):
        return self.choice_text

我正在尝试创建问题的模型形式。

class QuestionForm(forms.ModelForm):
    class Meta:
        model = Question
        field = ['question_test','pub_date','question_type']

我想要表格中的以下功能,首先应要求提供question_textpub_datequestion_type

如果我选择question_type等于'SELECT_ONE_CHOICE',则应该出现一个add_choices+按钮,并且该按钮使我们能够在文本字段框中输入n个选项(一个接一个) ,请点击add_choices+ n次)。并且这些选择也应反映在related_name属性q_choice中(创建n q_choicesave() question model)。

如果我选择question_type等于'SELECT_ALL_CHOICE',则应该发生类似的序列操作,并最终应保存QuestionForm。

稍后我可以使用单选按钮或复选框显示问题,具体取决于question_type(我知道如何编码)

如何使用Django的模型形式完成此操作?基本上,在创建问题时,这些与表单和模型的中间交互将如何发生? 请帮助(可能需要一些代码)

谢谢!

0 个答案:

没有答案
相关问题