Reputation: 245
Situation: I have a form that is used for search and I return the same form on the results page for the user to filter their results. To get rid of garbage input, I have implemented a clean_xxx method.
Unfortunately, the form is returned on the results page with the garbage input even though it was cleaned. How can I get the clean data to display?
Here are a few ideas:
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...
}
Thanks for your help.
Upvotes: 7
Views: 1019
Reputation: 8324
Whatever you return from a 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 it doesn't do that, then odds are the trouble is in the validation logic of your method.
Upvotes: 1