Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

verbose_name for a model's method

How can I set a verbose_name for a model's method, so that it might be displayed in the admin's change_view form?

example:

class Article(models.Model):
    title = models.CharField(max_length=64)
    created_date = models.DateTimeField(....)
    def created_weekday(self):
        return self.created_date.strftime("%A")

in admin.py:

class ArticleAdmin(admin.ModelAdmin):
    readonly_fields = ('created_weekday',)
    fields = ('title', 'created_weekday')

Now the label for created_weekday is "Created Weekday", but I'd like it to have a different label which should be i18nable using ugettext_lazy as well.

I've tried

    created_weekday.verbose_name=...

after the method, but that did not show any result. Is there a decorator or something I can use, so I could make my own "verbose_name" / "label" / whateverthename is?

like image 743
mawimawi Avatar asked May 23 '10 18:05

mawimawi


People also ask

What is the use of Verbose_name in Django model?

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.

How do you use verbose name?

Verbose Field Names are optional. They are used if you want to make your model attribute more readable, there is no need to define verbose name if your field attribute is easily understandable. If not defined, django automatically creates it using field's attribute name. Ex : student_name = models.

What is Verbose_name_plural in Django?

The verbose_name_plural [Django-doc] is a human readable name you give to the objects. You can use this in forms, dialogs, and other means to communicate with the user. There are no naming conventions (like PEP-8 for example), since this deals with communication between the app and the user.


1 Answers

list_display

created_weekday.short_description = 'Foo'

This solution requires the method to be defined in the ModelAdmin class. You can call a Model method (eg: get_created_weekday) from ModelAdmin like:

def created_weekday(self, obj):
    return obj.get_created_weekday()
like image 144
Davor Lucic Avatar answered Sep 29 '22 09:09

Davor Lucic