Select Boxes and Database

61 views
Skip to first unread message

David Merrick

unread,
Dec 2, 2023, 3:28:20 PM12/2/23
to django...@googlegroups.com
Hi. I can put an item from the database into a select box ie Countries of the World. What I want to know is saying, having chosen New Zealand from the select box, how do I display all the cities of New Zealand in another select box.

The database has two tables. First one is Countries. The second table is cities with populations and the foreign key of Countries table.

Then having chosen Auckland a city in New Zealand I want to display 

Country
City
Population 

In a template.

I have done this in Php, Javascript and Mysql already.

Cheers Dave


--
Dave Merrick

TutorInvercargill


Email merri...@gmail.com

Ph   03 216 2053

Cell 027 3089 169

Mike Dewhirst

unread,
Dec 2, 2023, 5:53:17 PM12/2/23
to django...@googlegroups.com
On 3/12/2023 7:27 am, David Merrick wrote:
Hi. I can put an item from the database into a select box ie Countries of the World. What I want to know is saying, having chosen New Zealand from the select box, how do I display all the cities of New Zealand in another select box.

The database has two tables. First one is Countries. The second table is cities with populations and the foreign key of Countries table.

Then having chosen Auckland a city in New Zealand I want to display 

Country
City
Population 

In a template.

I have done this in Php, Javascript and Mysql already.

Check https://simpleisbetterthancomplex.com/tutorial/2018/01/29/how-to-implement-dependent-or-chained-dropdown-list-with-django.html

Also, I recently had a similar task with companies and divisions from querysets and had trouble using the form.__init__() method. Here is an alternative approach. You can tweak what the form displays by calling a form method - here set_division_queryset(). In other words, you can populate selection choices based on code elsewhere. In my case I did it from within the view code like this ...

# forms.py
class List_Import(forms.Form):
    ...
    division = forms.ModelChoiceField(
        required=False,
        empty_label="Must select a Division",
        queryset=Division.objects.none(),
    ...
    def set_division_queryset(self, divqs):
        self.fields["division"].queryset = divqs
        
    def clean(self):
        cleaned_data = super().clean()
        selected_division = cleaned_data.get('division')
        available_divisions = self.fields['division'].queryset
        if selected_division not in available_divisions:
            self.add_error('division', 'Invalid choice. Please select a valid division.')
        return cleaned_data
        
# views.py
@login_required(redirect_field_name="next")
@ensure_csrf_cookie
def list_import(request, template="list_import.html", context=None):
    ...
    # User model has get_company() method and Company has get_all_divisions()
    divqs = request.user.get_company().get_all_divisions()
    form.set_division_queryset(divqs)
    ...
    if request.method == 'POST':
        form = List_Import(request.POST, request.FILES)
        # because form.is_valid() needs available_divisions and we are
        # not using form.__init__(), we have to send divqs again
        form.set_division_queryset(divqs)
        if form.is_valid():
            ...


Cheers

Mike




Cheers Dave


--
Dave Merrick

TutorInvercargill


Email merri...@gmail.com

Ph   03 216 2053

Cell 027 3089 169
--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CA%2B%3DMcKYDfzhvQ8ueCKKccYX3gcQUmfoX9NXipqf%3DDipsXPzG7g%40mail.gmail.com.


-- 
Signed email is an absolute defence against phishing. This email has
been signed with my private key. If you import my public key you can
automatically decrypt my signature and be sure it came from me. Your
email software can handle signing.
OpenPGP_signature.asc

Vishesh Mangla

unread,
Dec 2, 2023, 6:00:04 PM12/2/23
to django...@googlegroups.com
Hi Mike ,
You can do the following using query parameters.
Create a separate endpoint /getcities?city=... . You send the state and get array of cities.
This endpoint would give you a json array of cities. 
On selection of state on the frontend, your event listener would make api call to above endpoint and get list of cities without a reload.

Thanks,
Vishesh 




Swarup Selvaraj

unread,
Dec 7, 2023, 9:31:20 AM12/7/23
to Django users
Hi David,

The functionality you are interested in is called as Cascading Dropdown.

Below are few examples recommended by Bing Chat powered by GPT-4:
  • django-cascading-dropdown-widget · PyPI: This is a package that provides a cascading-dropdown widget for django. It allows you to create a dropdown list that depends on the selection of another dropdown list. It has examples of how to use it with different models and choices generators.
  • How to Create Cascading Dropdown List in Django python: This is a tutorial that shows how to create a cascading/dependent dropdown list in django python using jQuery. It has the code for creating the models, views, urls, and template for the application.
  • Django/jQuery Cascading Select Boxes? - Stack Overflow: This is a question and answer thread that discusses how to create cascading select boxes in django using jQuery. It has some suggestions of how to use hidden fields, ajax calls, and custom widgets to achieve the desired functionality.
  • Cascading Dropdowns using Javascript - Stack Overflow: This is another question and answer thread that explains how to create cascading dropdowns using javascript. It has a simple example of how to use an object to store the options and a function to populate the select elements.

Regards,
SWARUP Selvaraj
Reply all
Reply to author
Forward
0 new messages