Django TextField / CharField removes spaces / blank lines

I just researched my โ€œmistakeโ€ and it turned out that a new function appeared in Django 1.9 that frees CharFields by default: https://docs.djangoproject.com/en/1.9/ref/forms/fields/#django.forms .CharField.strip

The same seams to apply to text fields. So, I found out why Django unexpectedly behaves differently than before, but is there an easy way to restore the previous default value for automatically generated admin forms?

I would like NOT to remove spaces while still using the automatically generated form from the admin. Is it still possible?

+9
source share
6 answers

If you are looking for a text / char field and do not want it to remove spaces, you can set strip = False in the form constructor method, and then use the form in the admin panel.

class YourForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(YourForm, self).__init__(*args, **kwargs) self.fields['myfield'].strip = False class Meta: model = YourModel fields = "__all__" 

Then you can use this form in the admin form=YourForm specifying form=YourForm in the admin.py file.

+4
source
 strip=False 

in the model field for CharFields.


Django TextField does not support this delete function, so you need to do it yourself. You can use the strip method.

 abc.strip() 
+6
source

Try using this:

 # fields.py from django.db.models import TextField class NonStrippingTextField(TextField): """A TextField that does not strip whitespace at the beginning/end of it value. Might be important for markup/code.""" def formfield(self, **kwargs): kwargs['strip'] = False return super(NonStrippingTextField, self).formfield(**kwargs) 

And in your model:

 class MyModel(models.Model): # ... my_field = NonStrippingTextField() 
+6
source

It seems like the best way to handle this is to create a custom admin form as follows:

 class CustomForm(forms.ModelForm): my_field = forms.CharField(strip=False, widget=forms.Textarea) class Meta: model = MyModel exclude = [] 

This will create a default form in which only my_field will be overwritten without it. ) This should be installed in the appropriate admin, of course. If someone knows an even simpler version. Please, say Me!

+2
source

I had this problem with the django-rest model serializer. The data in my text box has been cleared of spaces. Therefore, if you are trying to do this at the serializer level, you can specify the space parameter in the CharField serializer. Here is the source code signature .

And here are the rest of the CharField docs

 class SomeSerializer(serializers.ModelSerializer): content = serializers.CharField(trim_whitespace=False) class Meta: model = YourModel fields = ["content"] 
0
source

Try the following:

 my_field = models.CharField(max_lenght=255, strip=False) 
-2
source

All Articles