How can I filter the value selected in a Django model form based on a certain data condition?

Good day!

I have a model table in order to add data to this model. [Citizen_2]

I would like users to enter their country of residence first, it's like a simple one-field form.

And then a form of two fields - where it is proposed to select the country of residence from the value already entered in the (name_country) field. For example, I have users added three countries there.

Then they add the cities - for those respective countries.

In the drop-down form field, select a country and write down your city there. And send the data to the model table. It is necessary that the data be saved in such a way that the city corresponds to the country to which the user wrote it down in the form.

This is then used in the form to fill in the data. By country and its corresponding city in the main form.

How can I make it in the form of a model [Citizen_2] the city of the corresponding country was chosen. From data previously filled in by users?

Any information or help would greatly save me, please.


class Country(models.Model):
    name_country = models.CharField(max_length=150, db_index=True)

    def __str__(self):
        return self.name_country

class City(models.Model):
    name_city = models.CharField(max_length=150, db_index=True)

    def __str__(self):
        return self.name_city

class Citizen_1(models.Model):
    name_country = models.ForeignKey(Country, on_delete=models.CASCADE)
    name_city = models.CharField(max_length=150, db_index=True)

    def __str__(self):
        return self.name_country, self.name_city

class Citizen_2(models.Model):
    name_country = models.ForeignKey(Country, on_delete=models.CASCADE)
    name_city = models.ForeignKey(City, on_delete=models.CASCADE)
    birthday = models.DateField()
    profession = models.CharField(max_length=150)
    hobby = models.CharField(max_length=150)
Back to Top