开发者

auto populate when syncdb with fixture for django-site

i want to populate django_site table when i run after syncdb initially 开发者_运维问答how can i do that i have one site only


Simple solution is to create a initial_data.json fixture for the Sites app that will override the default.

For example, my fixture at /myproject/myapp/fixtures/initial_data.json:

[
  {
    "model": "sites.site", 
    "pk": 1, 
    "fields": {
      "domain": "myproject.mydomain.com", 
      "name": "My Project"
    }
  }
]

A little note: Because this is common data for the whole project, it might be a good idea to store the fixture to /myproject/fixtures/ or to an app /myproject/commons/ (like I do) instead storing it with just some app. This keeps the data to be easy to find and makes apps a little more reusable.

A second note: Django allows to use multiple initial_data.json fixtures in multiple apps (Using mixed set of initial_data.json and initial_data.yaml fixtures didn't work as expected though :P). They all will be automatically used to pre-populate the database when syncdb is run.

Some references:

  • Django - Providing initial data with fixtures
  • The second comment at a codespatter.com blog post


You can either use the admin interface, from the shell, or script it (if you're looking for an automated solution). Here's how to do it from the shell (and what you would put into the script):

[sledge@localhost projects]$ python manage.py shell
>>> from django.contrib.sites.models import Site
>>> newsite = Site(name="Test",domain="test.com")
>>> newsite.save()


If you want to do this automatically, try this

from django.contrib import sites
from django.db.models import signals
from django.conf import settings

def create_site(app, created_models, verbosity, **kwargs):
    """
    Create the default site when when we install the sites framework
    """
    if sites.models.Site in created_models:
        sites.models.Site.objects.all().delete()

        site = sites.models.Site()
        site.pk = getattr(settings, 'SITE_ID', 1)
        site.name = getattr(settings, 'SITE_NAME', 'Example')
        site.domain = getattr(settings, 'SITE_DOMAIN', 'example.com')
        site.save()

signals.post_syncdb.connect(create_site, sender=sites.models)

That code needs to be run whenever a management command is executed. So you could put it in management/__init__.py for any app. Then just add SITE_ID, SITE_NAME, and SITE_DOMAIN to your settings.py.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜