python - Is it possible to use request.POST as a dictionary input?
问题描述
In my django project, I collect membership data by HTML form and insert them into the database. There are the code samples:
models.py
class member(models.Model):
name = models.CharField(max_length=100,blank=True,null=True)
gender = models.CharField(max_length=10,blank=True,null=True)
profession = models.CharField(max_length=100,blank=True,null=True)
views.py:
def manage(request):
form_values = request.POST.copy()
form_values.pop('csrfmiddlewaretoken') # I don't need it.
add_member = member(**form_values)
add_member.save()
If HTML form input is: Rafi, Male, student
Database gets in list format: ['Rafi'], ['Male'], ['student']
How can I solve this?
解决方案
You can make use of the .dict()
[Django-doc] method here:
def manage(request):
form_values = request.POST.copy()
form_values.pop('csrfmiddlewaretoken')
add_member = member(**form_values.dict())
add_member.save()
If there are multiple values for the same key, it will take the last one.
That being said, it might be better to take a look at a ModelForm
[Django-doc] to validate data and convert it to a model object. This basically does what you do here, except with proper validation, removing boilerplate code, and furthermore it will not use the other keys. If here a user would "forge" a POST request with extra key-value pairs, the server will raise a 500 error.
推荐阅读
- shell - CGI 输出 Shell - md5sum 错误值
- javascript - HTML JAVASCRIPT:向页面元素添加随机值
- node.js - TypeError [ERR_INVALID_ARG_TYPE]:“原始”参数必须是函数 puppeteer node js 类型
- html - 如何在引导程序左侧、中心和右侧设置 3 个图像,因为我在图像上使用循环
- cloudinary - 向strapi添加云
- c# - 如何使用 EF.Function.FreeText 创建动态 linq
- go - 函数定义了未命名的参数,但调用者仍然传递值
- android - tinyAlsa 中的音频路由
- reactjs - 为什么 forEach 如果返回 []?
- r - 无法躲避 ggplot barplot 中的误差线