Enhancing models for the admin

The admin app is clever enough to figure out a lot of things from your model automatically. However, sometimes the inferred information can be improved. This usually involves adding an attribute or a method to the model itself (rather than at the ModelAdmin class).

Let's first take a look at an example that enhances the model for better presentation, including the admin interface:

# models.py class SuperHero(models.Model): name = models.CharField(max_length=100) added_on = models.DateTimeField(auto_now_add=True) def __str__(self): return "{0} - {1:%Y-%m-%d %H:%M:%S}".format(self.name, self.added_on) def get_absolute_url(self): return reverse('superhero.views.details', args=[self.id]) class Meta: ordering = ["-added_on"] ...

Get Django: Web Development with Python now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.