linked dropdown from same model

Below is the models.

class Place(models.Model):
    region = models.CharField(max_length=20)
    country = models.CharField(max_length=40, blank=True, null=True) 
    city = models.CharField(max_length=30, blank=True, null=True)

    def regions(self):
        return str(self.region)
    
    def countries(self):
        return str(self.country)

    def cities(self):
        return str(self. City)

class Remarks(models. Model)
    region = models.ForeignKey(Place, on_delete=models.PROTECT)
    country = models.CharField(max_length=40, blank=True, null=True)
    city = models.CharField(max_length=30, blank=True, null=True)
    ...................

There is a form where there are 3 separate fields for region, country, city. The form uses model ‘Remarks’
I am trying to achieve linked dropdowns. That upon selection of region, only linked country data will be populated in country dropdown. Similarly upon selection of country only linked city data will be populated in city dropdown.

Here is what I tried with forms.py 's init method.

places = Place()

        self.fields['region'].queryset=places.regions() 
        self.fields['country'].queryset = Place.objects.none() 

        if 'region' in self.data:
            try:
                region_id = int(self.data.get('region'))
                self.fields['country'].queryset = Place.objects.filter(region=region_id).values('country').order_by('country')
            except (ValueError, TypeError):
                pass 
        elif self.instance.pk:
            # self. Fields['country'].queryset = self. Instance.country
            pass

But currently I am facing the following error


'str' object has no attribute 'all'

highlighting the below line of the forms.py,


self.Fields['region'].queryset=places.Regions()

Please help to fix this issue. - Thank you!

Linked (sometimes referred to as cascade or chained) dropdowns are done with a mix of JavaScript and extra views.

Basically, JavaScript in the page needs to catch the “changed” event (whatever the proper name is) for each dropdown and call a view to update the dependent field.

You can find a number of discussions about this in the forum if you search for “cascade select”.

Almost all the examples shown were using more than 1 models and there is linking defined between models. But for me here, its within same model which is difficult to deal with. :frowning:

So, I did create 3 models totally and have the data separately to make it work as of now.

Glad you have it working, but 1 model vs 3 shouldn’t be an issue. It would be a matter of what information you pass to the view(s) and the queries being used to return the responses.