【问题标题】:How to create instance with pre-populated ChoiceField in form如何在表单中使用预填充的 ChoiceField 创建实例
【发布时间】:2020-11-30 05:52:34
【问题描述】:

这是我的 forms.py。我想在我的模型中创建具有默认“V”选项的实例。因此创建了实例,但选择了“A”,这是我在模型中默认提供的。

class VideoForm(forms.ModelForm):
    theory_type = forms.ChoiceField(choices=quests.StageTheories.THEORY_TYPE)

    class Meta:
       model = quests.StageTheories
       fields = ['title', 'youtube', 'stage']

class StageTheories(models.Model):
    THEORY_TYPE = (
        ('Q', 'Quiz'),
        ('A', 'Article'),
        ('V', 'Video'),
    )

    stage = models.ForeignKey(to=Stages, on_delete=models.CASCADE, db_column="stage_id",verbose_name="Этап", )
    title = models.CharField(max_length=47, db_column="title", verbose_name="Заголовок теории",)
    text = models.TextField(db_column="text", verbose_name="Текст теории", null=True, blank=True,)
    youtube = models.URLField(db_column="youtube", verbose_name="Ссылка на youtube", null=True, blank=True,)
    sortOrder = models.PositiveIntegerField(null=True, blank=True, db_column="sort_order", verbose_name="Порядковый номер", )
    theory_type = models.CharField(max_length=1, choices=THEORY_TYPE, default='A')

class AddVideoView(CreateView):
    model = quests.StageTheories
    form_class = VideoForm
    success_url = '/'
    template_name = 'add_video.pug'

    def get_initial(self):
        initial = super().get_initial()
        initial['stage'] = quests.Stages.objects.get(id=self.kwargs['pk'])
        initial['theory_type'] = 'V'
        return initial

初始值不用于表单数据吗?

【问题讨论】:

  • 在浏览器中我看到预先填充的“视频”选项,但是当我保存时,它会带来“文章”
  • 我只需要在类元中提供字段'theory_type',而不是覆盖

标签: django generics django-forms django-generic-views


【解决方案1】:

它是从哪里继承的? get_initial

我认为你可以尝试使用 def 初始化(...): 初始[] = 或者 self.fields['name'].initial

【讨论】:

  • 它继承自通用 CreateView
猜你喜欢
  • 1970-01-01
  • 2022-01-01
  • 2018-01-06
  • 1970-01-01
  • 1970-01-01
  • 2019-10-30
  • 1970-01-01
  • 2016-05-23
  • 1970-01-01
相关资源
最近更新 更多