Меню

Python manage py createsuperuser ошибка


Django


February 18, 2021

1 Minute

Error

When I tried to run this command: python manage.py createsuperuser in my Django project, it gave me a super long error which included the following:

File “manage.py”, line 22, in
main()
File “manage.py”, line 18, in main
execute_from_command_line(sys.argv)
File “/Users/username/.local/share/virtualenvs/django-learn-csZU2bYZ/lib/python3.8/site-packages/django/core/management/init.py”, line 364, in execute_from_command_line
utility.execute()

….

ImportError: cannot import name ‘path’ from ‘django.urls’ (/Users/username/.local/share/virtualenvs/django-learn-csZU2bYZ/lib/python3.8/site-packages/django/urls/init.py)

Solution

The problem in my case was that I had the wrong version of Django installed. In order to run the python manage.py createsuperuser command you need at least Django 2.

Run this command to check the version of Django you are currently working with:

python -m django --version 

Run this command to install the latest version of Django.

pip install --upgrade django

Run the python -m django --version command again and make sure your new Django version is 2.x or above. If so, you should be able to run python manage.py createsuperuser now

Published
February 18, 2021

Вобщем-то вот.

(env) fix@catiger:~/app$ python manage.py createsuperuser
Traceback (most recent call last):
  File "manage.py", line 22, in <module>
    main()
  File "manage.py", line 18, in main
    execute_from_command_line(sys.argv)
  File "/home/fix/env/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line
    utility.execute()
  File "/home/fix/env/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/fix/env/lib/python3.8/site-packages/django/core/management/base.py", line 330, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/home/fix/env/lib/python3.8/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 79, in execute
    return super().execute(*args, **options)
  File "/home/fix/env/lib/python3.8/site-packages/django/core/management/base.py", line 371, in execute
    output = self.handle(*args, **options)
  File "/home/fix/env/lib/python3.8/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 111, in handle
    username = self.get_input_data(self.username_field, message, default_username)
  File "/home/fix/env/lib/python3.8/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 209, in get_input_data
    raw_value = input(message)
UnicodeEncodeError: 'latin-1' codec can't encode characters in position 0-2: ordinal not in range(256)

Кусок settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'app.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'app.wsgi.application'


# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}


# Password validation
# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/

LANGUAGE_CODE = 'ru-ru'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/

STATIC_URL = '/static/'

Уже строго(!!!) по мануалу делаю. Четвёртый день.
Сначала без venv пробовал глобально всё поставить, там хоть страницу джанго увидел, но статика не работала. Снёс всё вместе с убунту и так много раз.
Теперь вот третья попытка с venv и всё время на этом месте такая петрушка.
Миграции прошли успешно.
Ах, да вот локаль.

root@catiger:~# locale -a | grep UTF-8
C.UTF-8

sudo su — postgres

psql

dj_crm=# d common_company

                                      Table "public.common_company"
   Column   |          Type           | Collation | Nullable |                  Default
------------+-------------------------+-----------+----------+--------------------------------------------
 id         | integer                 |           | not null | nextval('common_company_id_seq'::regclass)
 name       | character varying(100)  |           |          |
 address    | character varying(2000) |           |          |
 sub_domain | character varying(30)   |           | not null |
 user_limit | integer                 |           | not null |
 country    | character varying(3)    |           |          |

INSERT INTO common_company (name,sub_domain,user_limit,country) VALUES (‘Ombrella Corp’,’IT’,9999,’USA’);

dj_crm=# select * from common_company;

 id |     name      | address | sub_domain | user_limit | country
----+---------------+---------+------------+------------+---------
  2 | Ombrella Corp |         | IT         |       9999 | USA
(1 row)

q

exit

on file: common/models.py change default of company with id of your company ( in my test id = 2)

class User(AbstractBaseUser, PermissionsMixin):
    file_prepend = "users/profile_pics"
    username = models.CharField(max_length=100, unique=True)
    first_name = models.CharField(max_length=150, blank=True)
    last_name = models.CharField(max_length=150, blank=True)
    email = models.EmailField(max_length=255, unique=True)
    is_active = models.BooleanField(default=True)
    is_admin = models.BooleanField(default=False)
    is_staff = models.BooleanField(default=False)
    date_joined = models.DateTimeField(("date joined"), auto_now_add=True)
    role = models.CharField(max_length=50, choices=ROLES)
    profile_pic = models.FileField(
        max_length=1000, upload_to=img_url, null=True, blank=True
    )
    has_sales_access = models.BooleanField(default=False)
    has_marketing_access = models.BooleanField(default=False)
    company = models.ForeignKey(Company, on_delete=models.CASCADE,default=2)

save file and do :

python manage.py makemigrations

Migrations for 'common':
  common/migrations/0022_auto_20200612_1404.py
    - Alter field company on user

python manage.py migrate

Operations to perform:
  Apply all migrations: accounts, auth, cases, common, contacts, contenttypes, emails, events, invoices, leads, marketing, opportunity, planner, sessions, tasks, teams, thumbnail
Running migrations:
  Applying common.0022_auto_20200612_1404... OK

python manage.py createsuperuser

Email: dr.oswell@ombrellacorp.com
Username: crm
Password:
Password (again):
Superuser created successfully.

tl;dr

When you need to create a superuser, the official Django documentation says to run django-admin.py createsuperuser. Instead, run the following:

$ python manage.py createsuperuser

The Details

While putting together a tutorial for Django, I started to explore how a project behaves if I didn’t create a superuser when running syncdb for the first time. My first question was how do you create a superuser after running syncdb.

I found the following documentation to create a superuser:

django-admin.py createuser

django-admin.py createuser

https://docs.djangoproject.com/en/1.5/ref/django-admin/#django-admin-createsuperuser

Following the documentation, I ran django-admin.py createsuperuser and got an “unknown command error.” Here is the full output for this set of steps:

(djangobox)$ python manage.py syncdb
Creating tables ...
Creating table auth_permission
Creating table auth_group_permissions
Creating table auth_group
Creating table auth_user_groups
Creating table auth_user_user_permissions
Creating table auth_user
Creating table django_content_type
Creating table django_session
Creating table django_site

You just installed Django's auth system, which means you don't have any superusers defined.
Would you like to create one now? (yes/no): no
Installing custom SQL ...
Installing indexes ...
Installed 0 object(s) from 0 fixture(s)
(djangobox)$ django-admin.py createsuperuser
Unknown command: 'createsuperuser'
Type 'django-admin.py help' for usage.
(djangobox)$ 

So I looked in my project’s settings.py to find that django.contrib.auth was indeed installed. So what gives? In my opinion, the official Django documentation is wrong or misleading, depending on which side of the hair you split. Let me explain.

When you create a superuser, you are creating one for a specific project. Therefore django-admin.py needs to know which project is the target. The conventional way to perform commands on existing projects is to use manage.py, which provides the project and settings information for the Django admin tools. To create a superuser for a Django project, run the following:

$ python manage.py createsuperuser

This allows us to create a superuser if we said no when we ran python manage.py syncdb to instantiate the initial project database. We can also add additional superusers if we want.

Back to the error we got when we tried to create a superuser with django-admin:

(djangobox)$ django-admin.py createsuperuser
Unknown command: 'createsuperuser'
Type 'django-admin.py help' for usage.
(djangobox)$ 

The reason this command failed is that the createsuperuser command is from the django.contrib.auth package, which is not loaded when you run django-admin.py with the default installation configuration (at least without specifying a project or database). These tools, django-admin.py and the project specific manage.py are convenience scripts around ManagementUtility in the django.core.management package. This utility system is extensible. When you add a package to the INSTALLED_APPS dictionary in a project’s settings.py file, it will add management commands, if it has any, to manage.py. Run manage.py without parameters, and you will see what commands are available:

Available subcommands:

[auth]
    changepassword
    createsuperuser

[django]
    cleanup
    compilemessages
    createcachetable
    dbshell
    diffsettings
    dumpdata
    flush
    inspectdb
    loaddata
    makemessages
    runfcgi
    shell
    sql
    sqlall
    sqlclear
    sqlcustom
    sqlflush
    sqlindexes
    sqlinitialdata
    sqlsequencereset
    startapp
    startproject
    syncdb
    test
    testserver
    validate

[sessions]
    clearsessions

[staticfiles]
    collectstatic
    findstatic
    runserver

when you run django-admin.py on its own, it only shows what is under the [django] list of subcommands.

When you read the source code to django-admin.py, you’ll see something like the following:

#!/Users/jbaldwin/code/djangobox/bin/python
from django.core import management

if __name__ == "__main__":
management.execute_from_command_line()

When you read the source code to manage.py, you’ll see something like:

#!/usr/bin/env python
import os
import sys 

if __name__ == "__main__":
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")

    from django.core.management import execute_from_command_line

    execute_from_command_line(sys.argv)

You see the commonality: both call django.core.management’s method execute_from_command_line.  This function is a wrapper around the ManagementUtility class in the django.core.management package. No project contexts are provided to django-admin.py, but is provided in manage.py. The directory which contains manage.py will have the project directory (in this case “mysite”), which has the project’s settings.py file. manage.py sets an environment variable for the project and the settings file, then calls the convenience function, passing our parameters to it. If you are interested in poking around the Django source, ManagementUtility is in django.core.management.__init__.py.

To continue on with my explanation, lets look to the official Django docs. Read the red underlined text.

django-admin-manage-py

This is not actually the case. manage.py does not wrap around django-admin.py. I’m not clear why this is stated. This is, in implementation, not accurate. They are both thin wrappers around django.core.management. There could be a misunderstanding of the documentation writers that got carried forward and hasn’t been fixed. It could have been how Django operated prior to version 1.0. Or it is a conceptual simplification: The interface behavior of manage.py acts as if it is a thin wrapper around django-admin.py, since it provides the project specific context, while django-admin.py does not. At this time, I don’t know, and this is a minor nit about the generally excellent documentation, which has helped Django gain its popularity. My thanks to the documenters for all their good work.

Hopefully this post has shed light on some of the mechanics of the Django admin scripts. The main takeaway should be that when you read the djangodocs and they use django-admin.py for commands specific to a project and that project is not part of the parameters, then use manage.py instead.

Попытка создать суперпользователя для моей базы данных:

manage.py createsuperuser

Получение грустного рекурсивного сообщения:

Создание суперпользователя пропущено из-за отсутствия работы в TTY. Вы можете запустить manage.py createsuperuser в своем проекте, чтобы создать его вручную.

Серьезно Django? Серьезно?

Единственная информация, которую я нашел для этого, была приведена выше, но она не работала:
Невозможно создать суперпользователя в django из-за отсутствия работы в TTY

И этот другой здесь, который в основном тот же:
Невозможно создать суперпользователя Django

4b9b3361

Ответ 1

Если вы запустите

$ python manage.py createsuperuser
Superuser creation skipped due to not running in a TTY. You can run manage.py createsuperuser in your project to create one manually.

из Git Bash и обратитесь к приведенному выше сообщению об ошибке, попробуйте добавить winpty

i.e, например:

$ winpty python manage.py createsuperuser
Username (leave blank to use '...'):

Чтобы иметь возможность запускать команды python, как обычно, в Windows, а также то, что я обычно делаю, это добавить строку псевдонима в файл ~/.profile i.e.

 MINGW64 ~$ cat ~/.profile
 alias python='winpty python'

После этого либо отправьте файл ~/.profile, либо просто перезапустите терминал, а начальная команда python manage.py createsuperuser должна работать как ожидалось!

Ответ 2

Я собираюсь предположить, что если вы используете manage.py createsuperuser, а не python manage.py createsuperuser, вы используете команду из среды IDE или какой-либо другой странной среды. Попробуйте запустить python manage.py createsuperuser вне вашей среды разработки, и он должен работать. В идеале вы бы использовали виртуальную среду или virtualenvwrapper.

Ответ 3

У меня была такая же проблема при попытке создать суперпользователя в контейнере докера с помощью команды: sudo docker exec -i <container_name> sh. Добавление опции -t решило проблему:

sudo docker exec -it <container_name> sh

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Python int input ошибка
  • Python import pandas ошибка