I have an abstract class with name and slug field.when i inherit from another class i want to change verbose_name parameter according to that class. How can I set this properties? I want to set the verbose_name parameter of the name field to "foo". but I want to use different parameter data for two different classes.
An example:
For ProductModel name field verbose_name="Foo"
For CategoryModel name field verbose_name="Poo"
class BaseProductModel(models.Model):
name = models.CharField(max_length=200)
slug = AutoSlugField(populate_from="name",unique=True,verbose_name="Slug")
class Meta:
abstract=True
class ProductModel(BaseProductModel):
# I want to set the verbose_Name parameter of the name field to "foo".
#The two fields (name and slug) come from the inherited (BaseProductModel) class.
description = models.TextField(max_length=500,verbose_name="Detay")
class CategoryModel(BaseProductModel):
# The two fields (name and slug) come from the inherited (BaseProductModel) class.
# I want to set the verbose_Name parameter of the name field to "Poo".
def __str__(self):
return self.name
CodePudding user response:
You can do this in two ways
First, works only for abstract classes, otherwise it will change verbose_name of parent class too:
class ProductModel(BaseProductModel):
# I want to set the verbose_Name parameter of the name field to "foo".
#The two fields (name and slug) come from the inherited (BaseProductModel) class.
description = models.TextField(max_length=500,verbose_name="Detay")
ProductModel.get_field('name').verbose_name = 'Foo'
And second, do that in the __init__
method:
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
field = self._meta.get_field('name')
field.verbose_name = 'Foo'