Create empty queryset by default in django form fields

后端 未结 2 710
抹茶落季
抹茶落季 2021-01-30 08:09

I have this fields in form:

city = forms.ModelChoiceField(label=\"city\", queryset=MyCity.objects.all())
district = forms.ModelChoiceField(label=\"district\", qu         


        
2条回答
  •  盖世英雄少女心
    2021-01-30 08:26

    @radtek's comment should be an answer as it is useful in similar scenarios but with different approach than the accepted answer.

    If your queryset changes with the url in your view.

    I am extending the answer with example as I used:

    def my_view(request):
        ...
        form = YourForm(initial={'field1':value1, 'field2':value2})
        form.fields['field3'].queryset = YourModel.objects.filter('foo'=bar)
    

提交回复
热议问题