How can I make the selection value in the model form Django based on the value selected above?

Good day!

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

At me in the field the country is selected by the user. The form then records the city based on the selected country value.

You need to save them in the [Citizen_2] table model so that the city corresponds to its country in the corresponding fields. I've been thinking about how to do this for a week now. I would be very grateful for any hints.

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?

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_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