在def __init__中定义ModelChoiceField的初始值

时间:2018-11-17 09:24:41

标签: django django-forms

我正在努力弄清为什么我不能使用form.py中def init 中指示的值来填充管辖区域。我设置此字段的初始值的方式是否有问题?

class TaxEditForm (forms.ModelForm):  
jurisdiction = forms.ModelChoiceField(queryset=State.objects.all())    

class Meta:
    model = Tax
    exclude = ('user', 'taxtype',)

def __init__(self, *args, **kwargs):

    self.taxtype = kwargs.pop('taxtype',None)
    self.jurisdiction = kwargs.pop('jurisdiction',None)
    super(TaxEditForm, self).__init__(*args, **kwargs)

    if self.taxtype == 1:
        self.fields['jurisdiction'].choices = [(t.id, t) for t in State.objects.all()]
        self.fields['jurisdiction'].queryset = State.objects.all()

        self.fields['jurisdiction'].initial = State.objects.get(name=self.jurisdiction)

    elif self.taxtype == 2:
        self.fields['jurisdiction'].choices = [(t.id, t) for t in Country.objects.all()]
        self.fields['jurisdiction'].queryset = Country.objects.all()
        self.fields['jurisdiction'].initial = Country.objects.filter(name=self.jurisdiction)

谢谢!

2 个答案:

答案 0 :(得分:0)

弄清楚了。我必须在视图中的表单上设置初始值。

if taxtype == 2:
    jur = Country.objects.get(name=jurisdiction)
    jurid = jur.id
elif taxtype == 1:
    jur = State.objects.get(name=jurisdiction)
    jurid = jur.id
else:
    jurid = None

form = TaxEditForm(request.POST or None, request.FILES or None, instance=instance, initial={'jurisdiction': jurid}, taxtype=taxtype)

答案 1 :(得分:0)

如果您替换以下代码的两个实例,则您的ModelForm应该可以工作:

self.fields['jurisdiction'].initial =

...与...

self.initial['jurisdiction'] =