首页 > 解决方案 > 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?

标签: pythondjangoformsrequest

解决方案


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.


推荐阅读