Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django TextField and CharField is stripping spaces and blank lines

I just researched my "bug" and it turned out to be a new feature in Django 1.9 that CharFields strip spaces by default : https://docs.djangoproject.com/en/1.9/ref/forms/fields/#django.forms.CharField.strip

The same seams to apply to text fields TextField.

So I found out why Django suddenly behaves differently than before, but is there an easy way to restore the previous default for auto generated admin forms?

I would like to NOT strip spaces while still using the auto generated form from the admin. Is that still possible?

like image 401
Andy Avatar asked Aug 17 '16 11:08

Andy


People also ask

What is the difference between CharField and TextField in Django?

TextField can contain more than 255 characters, but CharField is used to store shorter length of strings. When you want to store long text, use TextField, or when you want shorter strings then CharField is useful.

What does CharField mean in Django?

CharField is a commonly-defined field used as an attribute to reference a text-based database column when defining Model classes with the Django ORM. The Django project has wonderful documentation for CharField and all of the other column fields.

What is TextField in Django?

TextField is a large text field for large-sized text. TextField is generally used for storing paragraphs and all other text data. The default form widget for this field is TextArea.


2 Answers

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

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__"

You can then use this form in the admin by specifying form=YourForm in the admin.py file.

like image 94
Shahrukh Mohammad Avatar answered Sep 22 '22 10:09

Shahrukh Mohammad


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's 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()
like image 41
Udi Avatar answered Sep 22 '22 10:09

Udi