djangodjango-modelsdjango-commands

Django commands cron ImportError: cannot import name


I want to add the models to the 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

What's the problem? I tried to do so:

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

But it did not help.


Solution

  • The below should work. You must make sure the Python/Django package askmoiseev is importable. To make it importable the simplest way is to set your current working directory as the directory on which the package askmoiseev exists.

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