简体   繁体   中英

Python - Django - Input validation

How can I make a validation for post fetch input? I manually validate if the first digit has empty space or isalnum to make update operation as below but I wonder is there a better approach?

def update_user_meta(request):
    if request.method == "POST":
    name = request.POST.get("name")
    if name is not None and name[0:1].isalnum() == True:
            selectedUser.name = name
    else:
            selectedUser.name = selectedUser.name

You should use django forms https://docs.djangoproject.com/en/3.2/topics/forms/ .

Unless this view is an API then use the serializers from the django rest framework.https://www.django-rest-framework.org/api-guide/serializers/

There are built-in functions to make field validations. It can be done with Regex Validator.

List of them are in the documents. https://docs.djangoproject.com/en/3.2/ref/validators/

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