[Answer]-Django createview, how to reset the initial value in the form?

1πŸ‘

βœ…

In your DepartFormCreateView view you have defined fields as list as

fields = ['depth', 'orders', 'lead', 'name','type','Unit','parent']

And in in get() method you are trying to do

self.fields['Unit'].queryset = ...

Here you are accessing list element using string 'Unit' as index, which is not valid in python.

I think you may want to use self.form.fields

self.form.fields['Unit'].queryset = ....
πŸ‘€Rohan

0πŸ‘

thanks rohan, your answer helps me a lot, and after a few hours debugging, i finally find the solution. here it is.

    def get(self, request, *args, **kwargs):
        #form_class = self.get_form_class()
        #form = self.get_form(form_class)
        #form.fields['Unit'].queryset = Units.objects.filter(status = 200, parent__id = 2)
        formview = super(DepartFormCreateView, self).get(request, *args, **kwargs)
        formview.context_data['form'].fields['Unit'].queryset = Units.objects.filter(status = 200, parent__id = 2)
        return formview

what i need to do is to reset the form value before it randers to html.

πŸ‘€leffe

Leave a comment