Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative to the deprecated setup_environ() for one-off django scripts?

Tags:

django

I used setup_environ() a while back to write a one-off python script to be run from the command line that didn't really fit very well at all as a custom manage.py command (my preferred choice). It set up everything nicely. I assume we deprecated this function because non-django pythonistas make fun of djangonauts for magicky stuff like this and we got tired of feeling dirty. So if its deprecated, what's the alternative? Maybe this is a lazy question, but what do i need to run in place of setup_environ to acheive the same effect? I guess I could copy/paste the function into my script but I'm assuming that wasn't the point of deprecating it. (obviously I can still use a deprecated function, but I want my script to survive a few versions of django)

like image 728
B Robster Avatar asked Feb 24 '13 05:02

B Robster


2 Answers

This has changed in Django 1.7

import os
import django
from myapp import models

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myapp.settings")
django.setup()

print models.MyModel.objects.get(pk=1)
like image 180
Ben Davis Avatar answered Nov 20 '22 20:11

Ben Davis


To expand on miki725's answer, if before you had

from django.core.management import setup_environ

import fooproject.settings as settings
setup_environ(settings)

just replace with

import os

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "fooproject.settings")
from django.conf import settings

and your settings will loaded as settings.

For Django 1.7+, see the solution from Ben Davis.

like image 28
Mark Chackerian Avatar answered Nov 20 '22 18:11

Mark Chackerian