简体   繁体   中英

How to use variables in ModelChoiceField queryset in Django

I am trying to use a specific list of data in my form with Django. I am using ModelChoiceField to retrieve from the model the data I need to display in the form (to let the users select from a scolldown menu). My query is complicate because need two filters based on variables passed by views

I've tried to use the sessions but in form is not possible to import the session (based to my knowledge).

form.py

def __init__(self, pass_variables, *args, **kwargs):
   super().__init__(*args, **kwargs)
   self.fields['initiative'] = forms.ModelChoiceField(queryset=raid_User_Initiative.objects.filter(company=pass_variables[1], username=pass_variables[0]).values_list('initiative', flat=True))

view.py

pass_variables = ((str(request.user), companyname))
f = Issue_form(pass_variables)

If I don't pass the variable the process works. The problem is with the code above as the form don't provide any error but it doesn't pass the if f.is_valid():

Thanks

I solved myself! Anyway if anyone interested the solution is using the sessions:

form.py

Before I declare the queryset as:

initiative = forms.ModelChoiceField(queryset=raid_User_Initiative.objects.all(), to_field_name="initiative")

And it is very important to use the , to_field_name="initiative"

After I amend the queryset as:

def __init__(self, user, company, *args, **kwargs):
        super(raid_Issue_form, self).__init__(*args, **kwargs)
        self.fields['initiative'].queryset = raid_User_Initiative.objects.filter(company=company, username=user).values_list('initiative', flat=True)

view.py

f = raid_Issue_form(request.user, request.session['company'])

Hope this help!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM