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?
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.
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.
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.
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With