Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

329
Visualizações
Where is a django validator function's 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 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.

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

From the docs:

A validator is merely a callable object or function that takes a value and simply returns nothing if the value is valid or raises a ValidationError 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.

over 4 years ago · Santiago Trujillo Relatório

0

Use URLField. It validates value and prepends http if neccessary.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda