Home > Enterprise >  Python - Django - Input validation
Python - Django - Input validation

Time:10-14

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

CodePudding user response:

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/

CodePudding user response:

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/

  • Related