Django命令cron ImportError:无法导入名称

时间:2014-06-01 09:27:04

标签: django django-models django-commands

我想将模型添加到命令中。 /home/max/askmoiseev/ask/management/commands/cron.py

# -*- coding: utf-8 -*-

from django.core.management.base import BaseCommand, CommandError
from ask.models import Tag


class Command(BaseCommand):

    def handle(self, *args, **options):
        print args

$ python manage.py cron

Traceback (most recent call last):
  File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 399, in execute_from_command_line
utility.execute()
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 392, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
 File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 272, in fetch_command
klass = load_command_class(app_name, subcommand)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 75, in load_command_class
module = import_module('%s.management.commands.%s' % (app_name, name))
  File "/usr/local/lib/python2.7/dist-packages/django/utils/importlib.py", line 40, in import_module
__import__(name)
  File "/home/max/askmoiseev/ask/management/commands/cron.py", line 4, in <module>
from ask.models import Tag
  File "/home/max/askmoiseev/ask/models.py", line 3, in <module>
from loginsys.models import User
  File "/home/max/askmoiseev/loginsys/__init__.py", line 3, in <module>
from ask.models import User
ImportError: cannot import name User

问题是什么? 我试图这样做:

#!/bin/bash
export DJANGO_SETTINGS_MODULE=askmoiseev.settings
./manage.py cron

但它没有帮助。

1 个答案:

答案 0 :(得分:2)

以下应该有效。您必须确保Python / Django包askmoiseev是可导入的。 要使其可导入,最简单的方法是将当前工作目录设置为包askmoiseev所在的目录。

import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'askmoiseev.settings'
from ask.models import Tag