verbose name on class field in django

Question:

I am need of help to add a verbose name.

class Address(models.Model) :
    
    class Zip(models.Field):
       def db_type(self, connection):
           return 'char(8)'

    zip            = Zip()
    address        = models.CharField(max_length=200, verbose_name="Rua")

        .....

Need put the verbose name of ZIP to CEP.

Asked By: Carlos Rocha

||

Answers:

Django models.Field.__init__() takes verbose_name as parameter you can set name there

class Address(models.Model):

    class Zip(models.Field):

        def __init__(self, max_length=8, *args, **kwargs):
            kwargs['verbose_name'] = "Zip code"
            self.max_length = max_length
            super().__init__(*args, **kwargs)

        def deconstruct(self):
            name, path, args, kwargs = super().deconstruct()
            del kwargs["verbose_name"]
            if kwargs.get("max_length"):
               del kwargs["max_length"]
            return name, path, args, kwargs

        def db_type(self, connection):
            return 'char(%s)' % self.max_length

    zip = Zip()
    address = models.CharField(max_length=200, verbose_name="Rua")

From Django-doc

The counterpoint to writing your init() method is writing the
deconstruct() method. It’s used during model migrations to tell Django
how to take an instance of your new field and reduce it to a
serialized form – in particular, what arguments to pass to init()
to re-create it.

If you haven’t added any extra options on top of the field you
inherited from, then there’s no need to write a new deconstruct()
method. If, however, you’re changing the arguments passed in
init() (like we are in HandField), you’ll need to supplement the values being passed.

Answered By: Ankit Tiwari
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.