django - dealing with windows line endings when doing max_length form validation

350 Views Asked by At

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?

1

There are 1 best solutions below

4
On BEST ANSWER

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