简体   繁体   中英

Get choice django with post request

I have found many solutions to get choice in Django field but they work when using a template such as get_foo_display

CATEGORY_CHOICES = (
        ('M', 'Male'),
        ('F', 'Female'),

But what I have to do if I need to get Male or Female with request.POST in views.py. Currently I am using request.POST['gender'] But this is giving me M or F

You would need to change M to Male and F to Female in the CATEGORY_CHOICES . The first term is the one that will be sent to the backend, the later one is the string the client will 'see'.

If I had a choice, I would do something like this,

choice_dict = {
    "M": "Male",
    "F": "Female"
}
CATEGORY_CHOICES = ((k, v) for k, v in choice_dict.items())

Then in views,

actual_value = choice_dict[request.POST['gender']]

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