简体   繁体   English

在 django 中验证 POST 请求的正文

[英]Validate body of a POST request in django

I have a view in django that sign's up a client and I have a model for the client and a form that looks like this:我在 django 中有一个视图,它注册了一个客户,我有一个 model 用于客户和一个看起来像这样的表格:

from django.forms import ModelForm
from api.models.client import Client


class SignUpForm(ModelForm):
    class Meta:
        model = Client
        fields = ['first_name', 'last_name']

In my view I would like to validate the data in the request but my problem is that the paramters in the request are camelCase and not snake_case so when I try to validate the data it doesn't work.在我看来,我想验证请求中的数据,但我的问题是请求中的参数是camelCase 而不是snake_case,所以当我尝试验证数据时它不起作用。

def sign_up(request):
    body = json.loads(request.body)
    form = SignUpForm(body)
    print(form.is_valid())
    return HttpResponse('this is a test response')

Is there a clean way of making this work?有没有一种干净的方法来完成这项工作? Also is this the correct way to do what I'm trying to do?这也是我想做的正确方法吗?

You can iterate through the body keys, use regex to rename the key and adding to a new dictionary.您可以遍历正文键,使用正则表达式重命名键并添加到新字典。

def camel_to_snake(val):
    return re.sub('([A-Z]+)', r'_\1', val).lower()

body = json.loads(request.body)
new_body = {camel_to_snake(k): v for k, v in body.items()}

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

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