- Author:
 - chrischambers
 - Posted:
 - September 2, 2011
 - Language:
 - Python
 - Version:
 - Not specified
 - Score:
 - 0 (after 0 ratings)
 
This simple snippet provides a more sensible default for the Site object created during the first pass of syncdb (that is, with a default domain of localhost:8000). I made this so that the admin's "view on site" button will work automagically during my development cycle (which often involves dropping and recreating a sqlite database).
In addition, it provides 2 options for configuring the default Site as you'd like: settings parameters (DEFAULT_SITE_DOMAIN and DEFAULT_SITE_NAME) or kwargs (the latter takes precedence).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31  | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
# Adapted From Http://stackoverflow.com/questions/1466827/ --
from django.conf import settings
from django.db.models import signals
from django.contrib.sites.models import Site
from django.contrib.sites import models as site_app
from django.contrib.sites.management import create_default_site as orig_default_site
signals.post_syncdb.disconnect(orig_default_site, sender=site_app)
# Configure default Site creation with better defaults, and provide
# overrides for those defaults via settings and kwargs:
def create_default_site(app, created_models, verbosity, db, **kwargs):
    name  = kwargs.pop('name', None)
    domain = kwargs.pop('domain', None)
    if not name:
        name = getattr(settings, 'DEFAULT_SITE_NAME', 'example.com')
    if not domain:
        domain = getattr(settings, 'DEFAULT_SITE_DOMAIN', 'localhost:8000')
    if Site in created_models:
        if verbosity >= 2:
            print "Creating example.com Site object"
        s = Site(domain=domain, name=name)
        s.save(using=db)
    Site.objects.clear_cache()
signals.post_syncdb.connect(create_default_site, sender=site_app)
 | 
More like this
- Add Toggle Switch Widget to Django Forms by OgliariNatan 1 month, 4 weeks ago
 - get_object_or_none by azwdevops 5 months, 2 weeks ago
 - Mask sensitive data from logger by agusmakmun 7 months, 2 weeks ago
 - Template tag - list punctuation for a list of items by shapiromatron 1 year, 9 months ago
 - JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 1 year, 9 months ago
 
Comments
Please login first before commenting.