简体   繁体   English

通过发布请求获取选择 django

[英]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我找到了很多解决方案来在 Django 领域中获得选择,但它们在使用诸如get_foo_display的模板时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.但是如果我需要在views.py中使用request.POST获取男性或女性,我必须做什么。 Currently I am using request.POST['gender'] But this is giving me M or F目前我正在使用request.POST['gender']但这给了我 M 或 F

You would need to change M to Male and F to Female in the CATEGORY_CHOICES .您需要在CATEGORY_CHOICES中将M更改为Male ,将F更改为Female 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']]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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