1

Because windows line ending are actually two characters (\r\n), max_length treats them as two characters. I want them to only be treated as one character.

What would be the best way to deal with this? I assume it would be best to convert the line endings, but where in the process would I do this?

Acorn
  • 49,061
  • 27
  • 133
  • 172

1 Answers1

4

You'll want to convert the line endings by overriding the form's clean_<fieldname>() method, or the more general clean() method. Before cleaning the data, Django will convert it to Python and validate it, so you'll also need to move the max_length validation into the overridden clean method. Also note that, "this method should return the cleaned data, regardless of whether it changed anything or not."

http://docs.djangoproject.com/en/dev/ref/forms/validation/

In your case, the code would look like this:

from django import forms
from string import replace

class YourForm(forms.Form):
    some_field = forms.CharField()
    # Your fields here

    def clean_some_field(self):
        max_length = 50
        data = self.cleaned_data["some_field"]
        data = replace(data, "\r", "")
        if len(data) > max_length:
            raise forms.ValidationError("some_field is too long!")
        return data
John Debs
  • 3,714
  • 2
  • 25
  • 35
  • This is fantastic, thank you! I'm struggling a bit though. The field gets cleaned, but validation is happening on the raw data. Should running `form.is_valid()` run validation on the form after all the fields have been cleaned? Or do I need to run `is_valid()` on something else? – Acorn Feb 06 '11 at 14:53
  • The problem is that `clean_()` is run after validation of things such as `max_length`. This means you have to do the validation of the length in `clean_()` and get rid of `max_length` from your field. Maybe you could update your answer? http://stackoverflow.com/questions/4914123/django-how-to-process-clean-a-field-before-validation – Acorn Feb 06 '11 at 17:22
  • Ah yeah, you're right. I'll update the answer, thanks for pointing that out. – John Debs Feb 06 '11 at 17:31
  • Can I use super to keep all the other validators? If so, do I place the data back in `self.cleaned_data['some_field']`? – dhill Oct 21 '13 at 12:53