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.
Client Side Rendering: An easy trick to speed up server side rendering is to just do it on the client. One strategy is to embed a json structure in the django template, and then have javascript build the HTML. This obviously defeats the purpose of django server side rendering, but it will result in a speedup.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With