Where is django authentication function return value stored?

In my django app, this is my validator.py

from django.core.exceptions import ValidationError from django.core.validators import URLValidator def validate_url(value): url_validator = URLValidator() url_invalid = False try: url_validator(value) except: url_invalid = True try: value = "http://"+value url_validator(value) url_invalid = False except: url_invalid = True if url_invalid: raise ValidationError("Invalid Data for this field") return value 

which is used to verify 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 a URL like google.co.in and return its value before returning from validate_url, it prints http://google.co.in , but when I try to get cleaned_data['url'] in my views, it still shows google.co.in . So, where does the value returned by my validator come back, and I need to explicitly change the clean () functions to change the value of the url field

Doc says the following:

The clean () method in the 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 raises a ValidationError, the check will stop and this error will be raised. This method returns clean data, which is then inserted into the cleaned_data dictionary of the form.

I'm still not sure where the return value of the validator is returned, and if you can change the cleaned_data dict using the validator.

+5
source share
2 answers

From docs :

A validator is simply a callable object or function that takes a value and simply returns nothing if the value is valid or throws a ValidationError if not.

The return value is simply ignored.

If you want to change the value, you can use the clean_ field for the forms, as described here :

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

Validators should only check the data, which is why this is why the return value of the validator is ignored.

You are looking for "cleaning" the data (converting them into a general form). Django Forms is responsible for clearing the data.

+7
source

Use URLField . It checks the value and adds http if necessary.

0
source

Source: https://habr.com/ru/post/1266752/


All Articles