Where is a django validator functions return value stored?

2024/9/30 19:06:12

In my django app, this is my validator.py

from django.core.exceptions import ValidationError
from django.core.validators import URLValidatordef validate_url(value):url_validator = URLValidator()url_invalid = Falsetry:url_validator(value)except:url_invalid = Truetry:value = "http://"+valueurl_validator(value)url_invalid = Falseexcept:url_invalid = Trueif url_invalid:raise ValidationError("Invalid Data for this field")return value

which is used to validate this :

from django import forms
from .validators import validate_url
class SubmitUrlForm(forms.Form):url = forms.CharField(label="Submit URL",validators=[validate_url])

When I enter URL like google.co.in, and print the value right before returning it from validate_url, it prints http://google.co.in but when I try to get the cleaned_data['url'] in my views, it still shows google.co.in. So where does the value returned by my validator go and do I need to explicitly edit the clean() functions to change the url field value??

The doc says the following:

The clean() method on a Field subclass is responsible for running to_python(), validate(), and run_validators() in the correct order and propagating their errors. If, at any time, any of the methods raise ValidationError, the validation stops and that error is raised. This method returns the clean data, which is then inserted into the cleaned_data dictionary of the form.

I am still not sure where the validator return value goes and if it is possible to change cleaned_data dict using the validator.

Answer

From the docs:

A validator is merely a callable object or function that takes a valueand simply returns nothing if the value is valid or raises aValidationError if not.

The return value is simply ignored.

If you want to be able to modify the value you may use clean_field on the forms as described here:

class SubmitUrlForm(forms.Form):url = ...def clean_url(self):value = self.cleaned_data['url']...return updated_value

Validators are only about validating the data, hence that is why the return value of the validator gets ignored.

You are looking for data "cleaning" (transforming it in a common form). In Django, Forms are responsible for data cleaning.

https://en.xdnf.cn/q/71051.html

Related Q&A

Modifying YAML using ruamel.yaml adds extra new lines

I need to add an extra value to an existing key in a YAML file. Following is the code Im using.with open(yaml_in_path, r) as f:doc, ind, bsi = load_yaml_guess_indent(f, preserve_quotes=True) doc[phase1…

How to get the background color of a button or label (QPushButton, QLabel) in PyQt

I am quite new to PyQt. Does anyone tell me how to get the background color of a button or label (QPushButton, QLabel) in PyQt.

Is it possible to make sql join on several fields using peewee python ORM?

Assuming we have these three models.class Item(BaseModel):title = CharField()class User(BaseModel):name = CharField()class UserAnswer(BaseModel):user = ForeignKeyField(User, user_answers)item = Foreign…

Django multiple form factory

What is the best way to deal with multiple forms? I want to combine several forms into one. For example, I want to combine ImangeFormSet and EntryForm into one form:class ImageForm(forms.Form):image =…

How to include the private key in paramiko after fetching from string?

I am working with paramiko, I have generated my private key and tried it which was fine. Now I am working with Django based application where I have already copied the private key in database.I saved m…

SHA 512 crypt output written with Python code is different from mkpasswd

Running mkpasswd -m sha-512 -S salt1234 password results in the following:$6$salt1234$Zr07alHmuONZlfKILiGKKULQZaBG6Qmf5smHCNH35KnciTapZ7dItwaCv5SKZ1xH9ydG59SCgkdtsTqVWGhk81I have this snippet of Python…

Running python scripts in Anaconda environment through Windows cmd

I have the following goal: I have a python script, which should be running in my custom Anaconda environment. And this process needs to be automatizated. The first thing Ive tried was to create an .exe…

How to work out ComplexWarning: Casting complex values to real discards the imaginary part?

I would like to use a matrix with complex entries to construct a new matrix, but it gives me the warning "ComplexWarning: Casting complex values to real discards the imaginary part".As a resu…

Is it possible to use POD(plain old documentation) with Python?

I was wondering if it is possible to use POD(plain old documentation) with Python? And how should I do it?

ctypes error AttributeError symbol not found, OS X 10.7.5

I have a simple test function on C++:#include <stdio.h> #include <string.h> #include <stdlib.h> #include <locale.h> #include <wchar.h>char fun() {printf( "%i", 1…