Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django alter form data in clean method

Tags:

forms

django

I have a django form that I want to custom clean. Instead of just specifying an error message like here (Django form and field validation), I'd like to just alter the field myself. I tried severl ways, but keep running into error like cleaned_data is immutable.

So to solve this I made a copy, changed it and reassigned it to self. Is this the best way to do this? Could/should I have handled this in the view? Making a copy seems poor form but I keep running into 'immutable' road blocks. Sample code below where I simply check if the subject has '--help' at the end, and if not add it. Thanks

def clean(self):
        cleaned_data=self.cleaned_data.copy()
        subject=cleaned_data.get['subject']
        if not subject.endswith('--help'):
            cleaned_data['subject']=subject+='--help'
        self.cleaned_data=cleaned_data
        return self.cleaned_data
like image 631
rich Avatar asked Mar 11 '11 16:03

rich


People also ask

What is form cleaned data in Django?

form. cleaned_data returns a dictionary of validated form input fields and their values, where string primary keys are returned as objects. form. data returns a dictionary of un-validated form input fields and their values in string format (i.e. not objects).

What is clean method in Django?

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.

How does Django validate form data?

You can use is_valid() when required to validate complete form-data. This validation will check for Python-datatypes. This function will return True or False (Python Data Types) in return.

How do you remove this field is required Django?

If yes try to disable this behavior, set the novalidate attribute on the form tag As <form action="{% url 'new_page' %}", method="POST" novalidate> in your html file.


1 Answers

The correct way to deal with this is by using the field specific clean methods.

Whatever you return from the clean_FOO method is what the cleaned_data will be populated with by the time it gets to the clean function.

Do the following instead:

def clean_subject(self):
        data = self.cleaned_data.get('subject', '')
        if not data:
             raise forms.ValidationError("You must enter a subject")
             # if you don't want this functionality, just remove it.

        if not data.endswith('--help'):
             return data += '--help'
        return data
like image 83
Yuji 'Tomita' Tomita Avatar answered Sep 22 '22 20:09

Yuji 'Tomita' Tomita