Django best practices: how to clean and display a form

Situation: I have a form that is used for search, and I return the same form on the results page so that the user can filter their results. To get rid of garbage input, I used the clean_xxx method.

Unfortunately, the form returns on the garbage input page even if it has been cleared. How can I display clean data?

Here are some ideas:

  • In the clean_xxx method, set the value self.data.xxx = cleaned_xxx
  • Re-initialize the new form with cleaned_data.

forms.py:

SearchForm: def clean_q(self): q = self.cleaned_data.get('q').strip() # Remove Garbage Input sanitized_keywords = re.split('[^a-zA-Z0-9_ ]', q) q = "".join(sanitized_keywords).strip() #TODO: Fix self.data['q'] = q return q 

views.py

  search_form = SearchForm(params, user=request.user) if search_form.is_valid(): # Build the Query from the form # Retrieve The Results else: # For errors, no results will be displayed _log.error('Search: Form is not valid. Error = %s' %search_form.errors) response = { 'search_form': search_form... } 

Thank you for your help.

+7
source share
1 answer

Whatever you return from the clean_xxx method is what will be displayed. So for example:

forms.py:

 class SearchForm(forms.Form): def clean_q(self): return "spam and eggs" 

In the above example, the field will say "spam and eggs."

If this is not the case, then the likelihood that the problem is related to the verification logic of your method

+1
source

All Articles