Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Best Practices: How to clean and render a form

Tags:

python

django

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:

  1. In the clean_xxx method, set the self.data.xxx = cleaned_xxx value
  2. Reinitialize a new form with the 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...
    }

Thanks for your help.

like image 202
Naqeeb Avatar asked Apr 10 '12 21:04

Naqeeb


People also ask

How can I make Django render faster?

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.

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).


1 Answers

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.

like image 96
pydanny Avatar answered Oct 12 '22 23:10

pydanny