Note that there are some explanatory texts on larger screens.

plurals
  1. PODjango: how to cleanup form fields and avoid code duplication
    primarykey
    data
    text
    <p>Quite often I need to filter some form data before using it (saving to database etc.) Let's say I want to strip whitespaces and replace repeating whitespaces with a single one in most of the text fields, in many forms. It's not difficult to do this using <code>clean_&lt;fieldname&gt;</code> methods:</p> <pre><code># Simplified model with two text fields class MyModel(models.Model): title = models.CharField() description = models.CharField() # Model-based form class MyForm(forms.ModelForm): class Meta: model = MyModel def clean_title(self): title = self.cleaned_data['title'] return re.sub(r'\s{2,}', ' ', title.strip()) def clean_description(self): description = self.cleaned_data['description'] return re.sub(r'\s{2,}', ' ', description.strip()) </code></pre> <p>It does exactly what I need, and has a nice side effect which I like: if user enters only whitespaces, the field will be considered empty and therefore invalid (if it is required) and I don't even have to throw a <code>ValidationError</code>.</p> <p>The obvious problem here is code duplication. Even if I'll create some function for that, say <code>my_text_filter</code>, I'll have to call it for every text field in all my forms:</p> <pre><code>from myproject.filters import my_text_filter class MyForm(forms.ModelForm): class Meta: model = MyModel def clean_title(self): return my_text_filter(self.cleaned_data['title']) def clean_description(self): return my_text_filter(self.cleaned_data['description']) </code></pre> <p>The question: is there any standard and simple way in Django (I use version 1.2 if that matters) to do this (like, for example, by adding property <code>validators = {'title': my_text_filter, 'description': my_text_filter}</code> to <code>MyModel</code>), or at least some more or less standard workaround? I've read about form validation and validators in the documentation, but couldn't find what I need there.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload