渲染 django.forms.fields.ChoiceField 对象

Render django.forms.fields.ChoiceField object

在我的 Django 项目中,我遇到了以下问题: 我想要一个动态的 Django 表单。在第一步中,第一个表单会询问用户一些事情。当我得到后方法时,变量应该用于生成新表单

我的views.py

def calc(request):
    if request.method =="POST":
        get_form = CalculationForm(request.POST)
        if get_form.is_valid():
            op = get_form.cleaned_data['op']
            ab = get_form.cleaned_data['ab']
            alternative = AlternativForm(optype = op, wsgroup = ab)
            return render(request, 'calculated_lensar.html', {"alternativ" : alternativ})

    else:
        form = CalculationForm()
        return render(request, 'calc.html', {'form': form})

第二种形式(postmethod)看起来像

class AlternativForm(forms.Form):

    praep_button = ((3, 'hallo'), (4, 'tschüss'))

    def __init__(self, optype, wsgroup, *args, **kwargs):
        super(AlternativForm, self).__init__(*args, **kwargs) #dont know for what this is standing
        self.optype = optype
        self.wsgroup = wsgroup
        self.values = self.read_db()
        self.praep_button = self.buttons()
        self.felder = self.blub()
        self.neu2 = self.myfield_choices()


    def read_db(self):
        import sqlite3
        ....
        return result #tuple with 15x5 elements

    def buttons(self):
        praep_button = []
        for i in self.values:
            praep_button.append((i[4], i[1]))
        return praep_button #Just formating result from read_db in tuple(15x2)

    def blub(self):
        return forms.ChoiceField(widget=forms.RadioSelect, choices=self.praep_button)

    myfield = forms.ChoiceField(widget=forms.RadioSelect, choices=praep_button) #print --><django.forms.fields.ChoiceField object at 0x751f9b90>

    def myfield_choices(self):

        field = self['myfield'] 


    """i think here is the problem. 
    Above 'myfield' is a django.forms.fields.ChoiceField object, but here it is rendered to html (like it should be). I have the code from  
    But instead i should use field = self.felder (radioselect woth tuple of the db)"""


        widget = field.field.widget

        attrs = {}
        auto_id = field.auto_id
        if auto_id and 'id' not in widget.attrs:
            attrs['id'] = auto_id
        name = field.html_name

        return widget.render(name, field.value(), attrs=attrs)
        #return widget.get_renderer(name, field.value(), attrs=attrs)

所以总而言之,我希望问题是清楚的。 如果我使用的是 AlternativForm(),我会得到常量形式。相反,我想获得一个动态形式。如果我在 views.py 中访问:

 alternative = AlternativForm(optype = op, wsgroup = ab)
 alternative = alternativ.felder

比我得到的。我可以将其渲染为 html 吗?

如果我在 forms.py 中设置:

 field = self.felder

比我得到的错误是它是一个字段而不是一个小部件

感谢阅读!

您只需在表单的 __init__() 方法中分配选项。几乎是你在做什么,但不是将 self.felder 定义为一个字段,你需要使用已经初始化的表单字段:

myfield = forms.ChoiceField(widget=forms.RadioSelect, choices=praep_button)

def __init__(self, optype, wsgroup, *args, **kwargs):
    super().__init__(*args, **kwargs)
    self.fields['myfield'].choices = self.get_choices(optype, wsgroup)  # create your choices in this method

def get_choices(optype, wsgroup):
    # call your other methods here
    return praep_button