简体   繁体   中英

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:

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.

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()}

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