Python question about positioning of "from... import" statement

閲覧: 113 回
最初の未読メッセージにスキップ

Daniel Grace

未読、
2014/10/01 11:37:372014/10/01
To: django...@googlegroups.com
Hi, this is more of a Python question but here is something I don't understand in a Django script.
The following script works fine:

import os
import django

if __name__ == '__main__':
    print("Starting Rango delete data script...")
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tango.settings')
    django.setup()
    from rango.models import Category, Page
    Page.objects.all().delete()
    Category.objects.all().delete()
    print("Deleted all data from tables: Page and Category.")

...but when I move the "from... import" statement to the top of the file:

import os
import django
from rango.models import Category, Page

if __name__ == '__main__':
    print("Starting Rango delete data script...")
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tango.settings')
    django.setup()
    Page.objects.all().delete()
    Category.objects.all().delete()
    print("Deleted all data from tables: Page and Category.")

...I get an error:

  File "C:\landy\lib\site-packages\django\conf\__init__.py", line 40, in _setup
    % (desc, ENVIRONMENT_VARIABLE))
django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TAB
LESPACE, but settings are not configured. You must either define the environment
 variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing s
ettings.

What is going on?

Thanks

Shai Efrati

未読、
2014/10/01 11:47:412014/10/01
To: django...@googlegroups.com
Hi!
If i'm not wrong, the reason is that you try to import rango.models before django.setup()

Try moving django.setup() after you import django and then your
from rango.models import Category, Page

Though i'm not sure it will work either, because you call:

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tango.settings')
after from rango.models import...

Let me know if that helped :)


Shai.


--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/955fb638-1724-4115-951a-668218e68771%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Daniel Grace

未読、
2014/10/01 12:26:122014/10/01
To: django...@googlegroups.com
OK, I should have read the warning on the Tango with Django page section 5.8:

"When importing Django models, make sure you have imported your project’s settings by that stage. If you don’t, an exception will be raised. This is why we import Category and Page towards the end of the population script, rather than at the top."
全員に返信
投稿者に返信
転送
新着メール 0 件