Search code examples
djangodjango-sites

How can I use the current Site as the default in a Django form using the Sites Framework?


I'm using the Sites Framework and want to save the current site as the default site value for one of my models.

Model:

class MyModel(models.Model):
    site = models.ForeignKey(
        Site, 
        on_delete=models.CASCADE, 
        default=Site.objects.get_current())  # THIS IS WHAT I WANT TO DO (DOESN'T WORK)
    ...other fields...

Is there a way to automatically save the current Site object as the site attribute of MyModel anytime I save a MyModel instance? Or would I need to do this manually by overriding either the form's or the model's save method, (or similar override)?


Solution

  • You can set the default site.

    models.py

    def get_current_site():
        return Site.objects.get_current().id
    
    
    class MyModel(models.Model):
        site = models.ForeignKey(
            Site,
            on_delete=models.CASCADE,
            default=get_current_site)
    

    This will only work if you have created a site in your database and also set the SITE_ID in settings.py