【问题标题】:Django: Dynamically generate ChoiceField values from another model objectDjango:从另一个模型对象动态生成 ChoiceField 值
【发布时间】:2020-09-16 06:42:43
【问题描述】:

我想用动态生成的 ChoiceField 选项实现一个 Django 表单。

在我的 views.py 中,我定义了以下(相关)方法:

from .forms import OptionForm

def get_choice():
  return # like this [(q.optionA, q.optionA), (q.optionB, q.optionB), (q.optionC, q.optionC), (q.optionD, q.optionD)]

# how can I pass q to this __init__ method
class OptionForm(forms.Form):
  options= forms.ChoiceField(choices= [])
  def __init__(self, *args, **kwargs):
    super(OptionForm, self).__init__(*args, **kwargs)    
    self.fields['options'].choices = get_choice()


def viewtest(request, test_pk):

# get the test object containing all the questions
# each question contains four options using which I want to generate ChoiceField options corresponding to each question
# each option is available as q.optionA, q.optionB q.optionC & q.optionD
  test= get_object_or_404(Test, pk= test_pk)
  options= []
  for q in test.questions.all():    
    opform= OptionForm() # how do I pass q.optionA, q.optionB q.optionC & q.optionD here to dynamically provide ChoiceField options?
    options.append(opform)
  return render(request, 'tests/test.html', {'test': test, 'options': options})

【问题讨论】:

    标签: python python-3.x django django-models django-forms


    【解决方案1】:

    要从模型中获得选择,@​​987654322@ 是一个更好的选择。在此处查找更多详细信息:https://docs.djangoproject.com/en/3.1/ref/forms/fields/#django.forms.ModelChoiceField

    【讨论】:

    • 不幸的是,这不能解决我的问题,因为我需要为每个问题设置单独的 ChoiceField 值。
    • 你能详细解释一下吗?我想你应该可以通过在 ModelChoiceField 中传递你的查询集来做到这一点。 forms.ModelChoiceField(queryset=YourModel.objects.filter() )
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-17
    • 1970-01-01
    • 1970-01-01
    • 2021-11-03
    • 2014-07-11
    • 2011-07-01
    相关资源
    最近更新 更多