Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to override the verbose name of a superclass model field in django

Let's say that I have a model Foo that inherits from SuperFoo:

class SuperFoo(models.Model):     name = models.CharField('name of SuperFoo instance', max_length=50)     ...  class Foo(SuperFoo):     ... # do something that changes verbose_name of name field of SuperFoo 

In class Foo, I'd like to override the verbose_name of the name field of SuperFoo. Can I? If not, is the best option setting a label inside the model form definition to get it displayed in a template?

like image 736
shanyu Avatar asked May 29 '09 19:05

shanyu


People also ask

How do I override a Django model?

Whenever one tries to create an instance of a model either from admin interface or django shell, save() function is run. We can override save function before storing the data in the database to apply some constraint or fill some ready only fields like SlugField.

What does verbose name mean in Django?

verbose_name is a human-readable name for the field. If the verbose name isn't given, Django will automatically create it using the field's attribute name, converting underscores to spaces. This attribute in general changes the field name in admin interface.

What is __ Str__ in Django?

str function in a django model returns a string that is exactly rendered as the display name of instances for that model.

What is def __ str __( self in Django?

def str(self): is a python method which is called when we use print/str to convert object into a string. It is predefined , however can be customised.


1 Answers

A simple hack I have used is:

class SuperFoo(models.Model):     name = models.CharField('name of SuperFoo instance', max_length=50)     ...     class Meta:          abstract = True  class Foo(SuperFoo):     ... # do something that changes verbose_name of name field of SuperFoo Foo._meta.get_field('name').verbose_name = 'Whatever' 
like image 125
Gerry Avatar answered Sep 20 '22 13:09

Gerry