How to prevent Django from auto-capitalizing of the verbose_name in models? E.g:
class TestModel(models.Model):
enb_id = models.IntegerField(null=True, v
if one needs all fields names to start with first character lowercase (e.g. in create forms), this can be set for label in css:
label:first-letter {
text-transform: lowercase;
}
I believe that the "most correct" answer in modern Django (v1.11+) is to do the following:
class TestModel(models.Model):
field_name = models.CharField(verbose_name=_('field name'), blank=True)
class TestModelForm(forms.ModelForm):
class Meta:
model = TestModel
fields = '__all__'
labels = {
'field_name': _('field name')
}
This doesn't require you to define a custom model field just to change the form, use custom CSS, or hack around browser behavior. It's laser-targeted to only change the string that gets sent to the form renderer for that one field, with absolutely no other potential knock-on effects.
Adding verbose_name in Meta class works for me.
from django.db import models
class Artist(models.Model):
name = models.CharField("Artist", max_length=255, unique=True)
class Meta:
verbose_name = "Artist"
verbose_name_plural = "aRTiStS"
result:
It seems that Django capitalizes the first letter when setting the form field for that model field:
...
defaults = {
'required': not self.blank,
'label': capfirst(self.verbose_name),
'help_text': self.help_text
}
You could create your own custom model field that overwrites the capfirst
(by passing the label as kwarg):
from django.db import models
class UpcappedModelField(models.Field):
def formfield(self, form_class=forms.CharField, **kwargs):
return super(UpcappedModelField, self).formfield(form_class=forms.CharField,
label=self.verbose_name, **kwargs)
It seems like the simple workaround for this is adding a whitespace at the beginning of verbose_name
. Function that performs the capitalization (capfirst
) changes only the first letter. If it is a whitespace nothing will be changed. Because web browsers ignore consecutive whitespaces everything will be displayed correctly.
class TestModel(models.Model):
enb_id = models.IntegerField(null=True, verbose_name=" eNB ID", blank=True)
class Meta:
verbose_name = " test model"