Book Image

Django Design Patterns and Best Practices

By : Arun Ravindran
Book Image

Django Design Patterns and Best Practices

By: Arun Ravindran

Overview of this book

Table of Contents (19 chapters)
Django Design Patterns and Best Practices
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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"]
        verbose_name = "superhero"
        verbose_name_plural = "superheroes"

Let's take a look at how admin uses all these non-field attributes...