How to stop auto-capitalization of verbose_name in django

后端 未结 5 806
野趣味
野趣味 2021-01-03 06:45

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         


        
相关标签:
5条回答
  • 2021-01-03 06:57

    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;
    }
    
    0 讨论(0)
  • 2021-01-03 07:04

    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.

    0 讨论(0)
  • 2021-01-03 07:07

    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: enter image description here

    0 讨论(0)
  • 2021-01-03 07:09

    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)
    
    0 讨论(0)
  • 2021-01-03 07:10

    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"
    
    0 讨论(0)
提交回复
热议问题