Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you extend the Site model in django?

What is the best approach to extending the Site model in django? Creating a new model and ForeignKey the Site or there another approach that allows me to subclass the Site model?

I prefer subclassing, because relationally I'm more comfortable, but I'm concerned for the impact it will have with the built-in Admin.

like image 585
John Giotta Avatar asked May 12 '10 18:05

John Giotta


2 Answers

As of Django 2.2 there still no simple straight way to extend Site as can be done for User. Best way to do it now is to create new entity and put parameters there. This is the only way if you want to leverage existing sites support.

class SiteProfile(models.Model):
    title = models.TextField()
    site = models.OneToOneField(Site, on_delete=models.CASCADE)

You will have to create admin for SiteProfile. Then add some SiteProfile records with linked Site. Now you can use site.siteprofile.title anywhere where you have access to current site from model.

like image 131
igo Avatar answered Oct 24 '22 22:10

igo


I just used my own subclass of Site and created a custom admin for it.

Basically, when you subclass a model in django it creates FK pointing to parent model and allows to access parent model's fields transparently- the same way you'd access parent class attributes in pyhon. Built in admin won't suffer in any way, but you'll have to un-register Sites ModelAdmin and register your own ModelAdmin.

like image 21
fest Avatar answered Oct 24 '22 23:10

fest