0

I have the following form:

class RegisterForm(UserCreationForm):
    company_role = forms.ModelChoiceField(queryset=CompanyRole.objects, empty_label='Select Company Role')
    office = forms.ModelChoiceField(queryset=Office.objects, empty_label='Select Office', required=False)
    location = forms.ModelChoiceField(queryset=Country.objects.all(), empty_label="Select Location", required=False)


    class Meta:
        model = User
        fields = ["first_name", "last_name", "username", "email", "password1", "password2", "company_role", "location",
                  "office"]



    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['office'].queryset = Office.objects.none()

Is it possible through this form to set office ModelChoiceField drop down to be required if the first item (id 1) is selected in company_role ModelChoiceField drop down and also if second item (id 2) is selected in company_role ModelChoiceField drop down then set location ModelChoiceField drop down to be required?

I have implemented AJAX dependent drop down which works fine but to further demonstrate, company role model has 2 records, id 1 - employee and id 2 - contractor.

In offices there are 3 records id 1 - office 1, id 2 - office 2, id 3 -office 3 and they each have the corresponding id to join to company role each record linked only to company role id 1 - employee.

The issue I'm having is when the user selects company role id 2 - contractor, the office is blank as there should not be any for the user to select which is what I wanted however the form is unable to submit as the office drop down is required.

I know I could set required = False but I want the user with company id 1 employee to be forced to select an office as they will be populated for the user with that company role.

I would greatly apprecaite some help on how to do this. Thanks in advance

Jimmy
  • 55
  • 1
  • 7
  • Hello @jimmy Check this link [Reference Link](https://simpleisbetterthancomplex.com/tutorial/2018/01/29/how-to-implement-dependent-or-chained-dropdown-list-with-django.html) – Akash senta Dec 31 '21 at 06:21
  • Also this [Link](https://stackoverflow.com/questions/25706639/django-dependent-select) will be helpful – Akash senta Dec 31 '21 at 06:23
  • @Akashsenta Thanks, but just so you know I have actually implemented what was in the guide (AJAX) when the user selects company role id 1 then offices will populate but if user selects company role id 2 then offices are blank which works as I expect. However the issue is when I set to required to force the user to select an option if they select company role id 2 and shows blank offices the form will not submit as the user has not selected an office but I don't want them to select an office as it should not be an option for company ide 2 if that makes sense? Thanks – Jimmy Dec 31 '21 at 07:17

0 Answers0