anexia-it / django-rest-passwordreset

An extension of django rest framework, providing a configurable password reset strategy
BSD 3-Clause "New" or "Revised" License
419 stars 148 forks source link

Cannot run migration on adding in INSTALLED_APPS #104

Closed whitebumblebee closed 3 years ago

whitebumblebee commented 4 years ago

I am trying to use it and following documentation. After adding it to INSTALLED_APPS inside settings.py file, when I try to run python manage.py migrate as shown in documentation, I get following error. Am I doing something wrong or missing something?

Traceback (most recent call last):
  File "manage.py", line 21, in <module>
    main()
  File "manage.py", line 17, in main
    execute_from_command_line(sys.argv)
  File "/home/shishir/Projects/performance_management/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line
    utility.execute()
  File "/home/shishir/Projects/performance_management/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 395, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/shishir/Projects/performance_management/venv/lib/python3.6/site-packages/django/core/management/base.py", line 328, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/home/shishir/Projects/performance_management/venv/lib/python3.6/site-packages/django/core/management/base.py", line 366, in execute
    self.check()
  File "/home/shishir/Projects/performance_management/venv/lib/python3.6/site-packages/django/core/management/base.py", line 395, in check
    include_deployment_checks=include_deployment_checks,
  File "/home/shishir/Projects/performance_management/venv/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 64, in _run_checks
    issues.extend(super()._run_checks(**kwargs))
  File "/home/shishir/Projects/performance_management/venv/lib/python3.6/site-packages/django/core/management/base.py", line 382, in _run_checks
    return checks.run_checks(**kwargs)
  File "/home/shishir/Projects/performance_management/venv/lib/python3.6/site-packages/django/core/checks/registry.py", line 72, in run_checks
    new_errors = check(app_configs=app_configs)
  File "/home/shishir/Projects/performance_management/venv/lib/python3.6/site-packages/django/core/checks/urls.py", line 13, in check_url_config
    return check_resolver(resolver)
  File "/home/shishir/Projects/performance_management/venv/lib/python3.6/site-packages/django/core/checks/urls.py", line 23, in check_resolver
    return check_method()
  File "/home/shishir/Projects/performance_management/venv/lib/python3.6/site-packages/django/urls/resolvers.py", line 407, in check
    for pattern in self.url_patterns:
  File "/home/shishir/Projects/performance_management/venv/lib/python3.6/site-packages/django/utils/functional.py", line 48, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/home/shishir/Projects/performance_management/venv/lib/python3.6/site-packages/django/urls/resolvers.py", line 588, in url_patterns
    patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
  File "/home/shishir/Projects/performance_management/venv/lib/python3.6/site-packages/django/utils/functional.py", line 48, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/home/shishir/Projects/performance_management/venv/lib/python3.6/site-packages/django/urls/resolvers.py", line 581, in urlconf_module
    return import_module(self.urlconf_name)
  File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 994, in _gcd_import
  File "<frozen importlib._bootstrap>", line 971, in _find_and_load
  File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 678, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/home/shishir/Projects/performance_management/performance_management/backend/urls.py", line 24, in <module>
    path('UMS/api/', include('django_rest_passwordreset.urls')),
  File "/home/shishir/Projects/performance_management/venv/lib/python3.6/site-packages/django/urls/conf.py", line 34, in include
    urlconf_module = import_module(urlconf_module)
  File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 994, in _gcd_import
  File "<frozen importlib._bootstrap>", line 971, in _find_and_load
  File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 678, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/home/shishir/Projects/performance_management/venv/lib/python3.6/site-packages/django_rest_passwordreset/urls.py", line 4, in <module>
    from django_rest_passwordreset.views import reset_password_request_token, reset_password_confirm, reset_password_validate_token
  File "/home/shishir/Projects/performance_management/venv/lib/python3.6/site-packages/django_rest_passwordreset/views.py", line 13, in <module>
    from django_rest_passwordreset.models import ResetPasswordToken, clear_expired, get_password_reset_token_expiry_time, \
  File "/home/shishir/Projects/performance_management/venv/lib/python3.6/site-packages/django_rest_passwordreset/models.py", line 26, in <module>
    class ResetPasswordToken(models.Model):
  File "/home/shishir/Projects/performance_management/venv/lib/python3.6/site-packages/django/db/models/base.py", line 115, in __new__
    "INSTALLED_APPS." % (module, name)
RuntimeError: Model class django_rest_passwordreset.models.ResetPasswordToken doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.
anx-cbenke commented 4 years ago

I just tried a fresh install with the quickstart-tutorial and then installed django-rest-passwordreset from pip and I encountered no such issues.

Have you installed everything from pip or directly from the repo? How does your project-structure look like? Could you post your settings.py?

whitebumblebee commented 4 years ago

Yes, i installed it with pip. My project structure looks something like this:

.
├── manage.py
├── assets
│   └── uni.svg
├── fabfile.py
├── fixtures
│   ├── initialReviewData.json
│   ├── initialRoleData.json
│   └── initialUserData.json
├── maintenance_off.html
├── templates
│   └── admin
├── frontend
│   ├── admin.py
│   ├── apps.py
│   ├── __init__.py
│   ├── models.py
│   ├── templates
│   ├── tests.py
│   ├── views.py
│   ├── src
│   ├── urls.py
│   ├── __pycache__
│   ├── migrations
│   └── static
├── static
│   ├── 137-1370051_avatar-generic-avatar-hd-png-download.png
│   ├── 428-4287240_no-avatar-user-circle-icon-png.png
│   ├── admin
│   ├── avatar-default-icon.png
│   ├── css
│   ├── img
│   ├── logorac.svg
│   ├── rest_framework
│   ├── unc.svg
│   ├── beolar.jpg
│   └── frontend
├── reviews
│   ├── apps.py
│   ├── __init__.py
│   ├── tests.py
│   ├── views.py
│   ├── admin.py
│   ├── models.py
│   ├── migrations
│   ├── urls.py
│   ├── serializers.py
│   ├── utils.py
│   ├── api.py
│   └── __pycache__
├── backend
│   ├── __init__.py
│   ├── wsgi.py
│   ├── asgi.py
│   ├── static
│   ├── prod_settings.py
│   ├── dev_settings.py
│   ├── local_settings.py
│   ├── urls.py
│   ├── settings.py
│   └── __pycache__
└── accounts
    ├── apps.py
    ├── __init__.py
    ├── managers.py
    ├── tests.py
    ├── views.py
    ├── drf_utils.py
    ├── exceptions.py
    ├── models.py
    ├── migrations
    ├── forms.py
    ├── admin.py
    ├── serializers.py
    ├── urls.py
    ├── api.py
    └── __pycache__

And my settings.py file looks something like this:

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = "jdiewjdewjfdjwfkdjf;lrejf;lekf;lkeqf;lkew;lfdkew"

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = [*]

# Application definition

INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    # Installed apps
    "rest_framework",
    "knox",
    "django_rest_passwordreset",
    "whitenoise.runserver_nostatic",
    # Created apps
    "accounts",
    "reviews",
    "frontend",
]

REST_FRAMEWORK = {
    "DEFAULT_AUTHENTICATION_CLASSES": ("knox.auth.TokenAuthentication",),
    "EXCEPTION_HANDLER": "rest_framework.views.exception_handler",
    # 'EXCEPTION_HANDLER':'accounts.exceptions.custom_exception_handler',
}

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

ROOT_URLCONF = "backend.urls"

TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [os.path.join(BASE_DIR, "templates")],
        "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 = "backend.wsgi.application"

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

DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.mysql",
        "NAME": "reviews_db",
        "USER": "xyz",
        "PASSWORD": "xxxxxxxxx",
        "HOST": "localhost",
        "OPTIONS": {
            "init_command": "SET foreign_key_checks = 0; "
            "SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ",
            "isolation_level": "repeatable read",
        },
    },
}

# Password validation
# https://docs.djangoproject.com/en/3.0/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.0/topics/i18n/

LANGUAGE_CODE = "en-us"

TIME_ZONE = "Asia/Kolkata"

USE_I18N = True

USE_L10N = True

USE_TZ = True

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

REACT_APP_DIR = os.path.join(BASE_DIR, "frontend")

STATICFILES_DIRS = (os.path.join(BASE_DIR, "assets"),)
STATIC_URL = "/static/"

AUTH_USER_MODEL = "accounts.Employee"

STATIC_ROOT = os.path.join(BASE_DIR, "static/")
try:
    from .local_settings import *
except ImportError as e:
    print(e)

EMAIL_HOST = "mail.xyz.com"
SERVER_EMAIL = "xyz1@xyz.com"
DEFAULT_FROM_EMAIL = "xyz2l@xyz.com"
DEFAULT_EMAIL_RECIPIENTS = []
whitebumblebee commented 4 years ago

I just tried installing it, then putting it inside INSTALLED_APPS in settings.py file and then tried the command python manage.py migrate and got above error. I dont what I am doing wrong.

anx-cbenke commented 4 years ago

Hmm, this appears to be a tricky one, I don't immediately see what is wrong. Could you please go through the quickstart-tutorial, test if everything works according to the tutorial and after that, install django-rest-passwordreset, add it to the INSTALLED_APPS and then run the migrations? I assume you will not have the same problem there. Maybe we can find the difference between the two projects this way.

Roconda commented 3 years ago

I had a similar error when upgrading. Found out that it was due to my user model importing the following:

from django_rest_passwordreset.models import ResetPasswordToken
from ... import ...

The solution was to move the import from the top of my user model to an inline import like:

class MyUser:
  def reset_password(self):
    from django_rest_passwordreset.models import ResetPasswordToken
    # your code

Hope this helps!

nezhar commented 3 years ago

@Roconda thanks for the solution

This is related to how Django is loading Apps and Models. You would get the same issue if you try to load a model in a custom queryset module for a manager.