简体   繁体   中英

Is it possible to get the value from an option in the drop down list in django?

So currently I am adding new data through a model I registered to the django's admin site whereby the model consists of 3 text fields (email, country, phone number). I am also doing a phone numbers validation with PyPI's phonenumbers package to validate if the entered number is a number that exists or is in wrong format. However in order to this validation, I need to parse the text in the country text field (for eg US) as an argument into the validation code to know if the number is real or fake and currently I can pass the text over but users will have to type in "US" instead of selecting from a list of countries like from a drop down list. I want to improve this format by implementing a drop down list to replace the current country text field with a list of countries to select from but when a user selects the country United States, on the front end it is supposed to display "United States" in the drop down list but the value, as in html context should be "US" and I want to instead parse "US" instead to the backend to do validation but still display the words "United States" for users to see. I currently have no clue of how to implement this and whether is it possible to get the value from the drop down list. Please tell me whether this is possible or any other methods I should look at.

For this purpose you need to add additional field to your database with short-code for country.

For example, instead of CharField you can use ForeignKey to new model called Country .

And this Country may be implemented like this:

class Country(models.Model):
    name = models.CharField(max_length=256)
    code = models.CharField(max_length=2)

    def __str__(self):
        return self.name

Or you can use Django Countries package , that includes all countries, their codes and flags (so instead of code you can show country flag). You can specify countries list there if you don't need them all.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM