skip to Main Content

I recently join with ongoing project which has done using Django framework and I am new to this framework. This code is not mine. When I run python manage.py runserver command I receive following error.

I have done all the configuration asked in readme file.

This is the local.py file

try:
    from .base import *
except ImportError:
    pass

from configparser import RawConfigParser


config = RawConfigParser()
config.read('/etc/django_settings/hopster_settings.ini')

SECRET_KEY = config.get('secrets', 'SECRET_KEY')

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

ALLOWED_HOSTS = []

INSTALLED_APPS += [
    'rest_framework_swagger',  # to enable swagger documentation for rest api
    'django_extensions',  # for print db schemas
]

DATABASES = {
    'default': {
        'ENGINE': config.get('database', 'DATABASE_ENGINE'),
        'NAME': config.get('database', 'DATABASE_NAME'),
        'USER': config.get('database', 'DATABASE_USER'),
        'PASSWORD': config.get('database', 'DATABASE_PASSWORD'),
        'HOST': config.get('database', 'DATABASE_HOST'),
        'PORT': config.get('database', 'DATABASE_PORT'),
    }
}

SITE_ID = 1

STATIC_URL = '/static/'

STATIC_NAME = 'hopster_static_cdn'
MEDIA_NAME = 'hopster_media_cdn'

STATICFILES_DIRS = [
    os.path.join(os.path.dirname(BASE_DIR), "static"),
    # '/var/www/static/',

]

STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), STATIC_NAME)


# STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'images', 'static')

# STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "english_vlog_static_cdn")

# media files on local server
MEDIA_URL = "/media/"
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), MEDIA_NAME)

STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
    'django.contrib.staticfiles.finders.DefaultStorageFinder',
)


REST_FRAMEWORK = {
    'DEFAULT_RENDERER_CLASSES': (
        'rest_framework.renderers.JSONRenderer',  # convert rest output into json format by ignoring browsable API
        'rest_framework.renderers.BrowsableAPIRenderer',  # to get the browsable API in web
    ),
    # 'DEFAULT_PARSER_CLASSES': (
    #     'rest_framework.parsers.JSONParser',
    # )
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.TokenAuthentication',
        # 'oauth2_provider.ext.rest_framework.OAuth2Authentication', Deprecated
        'oauth2_provider.contrib.rest_framework.OAuth2Authentication',
        # social authentication
        'rest_framework_social_oauth2.authentication.SocialAuthentication',
    ),
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticatedOrReadOnly',
        'rest_framework.permissions.IsAuthenticated',

    )
}

OAUTH_SINGLE_ACCESS_TOKEN = True
OAUTH2_PROVIDER = {
    'OAUTH_SINGLE_ACCESS_TOKEN': True,
    'OAUTH_DELETE_EXPIRED': True,
    # 'ACCESS_TOKEN_EXPIRE_SECONDS': 24 * 60 * 60,    # expires after 24 hours (default 10 hours = 36000s)
    # 'ACCESS_TOKEN_EXPIRE_SECONDS': 60 * 60,    # expires after 1 hour (default 10 hours = 36000s)
    'ACCESS_TOKEN_EXPIRE_SECONDS': 60 * 60 * 24 * 366,  # expires after 1 year

    'REFRESH_TOKEN_EXPIRE_SECONDS': 60,
    # this is the list of available scopes
    'SCOPES': {
        'read': 'Read scope',
        'write': 'Write scope',
        'groups': 'Access to your groups'
    }
}


AUTHENTICATION_BACKENDS = (
    # weixin a.k.a wechat oauth2
    # 'social_core.backends.weixin.WeixinOAuth2',

    # vk oauth2
    'social_core.backends.vk.VKOAuth2',

    # Others auth providers (e.g. Google, OpenId, etc)

    # Facebook OAuth2
    'social_core.backends.facebook.FacebookAppOAuth2',
    'social_core.backends.facebook.FacebookOAuth2',

    'oauth2_provider.backends.OAuth2Backend',

    # Google Oauth2
    'social_core.backends.google.GoogleOAuth2',

    # django-rest-framework-social-oauth2
    'rest_framework_social_oauth2.backends.DjangoOAuth2',

    # Django
    'django.contrib.auth.backends.ModelBackend',

    'oauth2_provider.backends.OAuth2Backend',

)

# fill these
SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = ''
SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = ''
SOCIAL_AUTH_GOOGLE_CLIENT_ID = ''


# for Gmail
EMAIL_USE_TLS = True
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = '[email protected]'
EMAIL_HOST_PASSWORD = 'Hopster@123'
EMAIL_PORT = 587
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER

This is the wsgi.py file

import os

from django.core.wsgi import get_wsgi_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "hopster.settings.local")

application = get_wsgi_application()

This is the error

Traceback (most recent call last):
File “manage.py”, line 22, in
execute_from_command_line(sys.argv)
File “F:Python ProjectHopster Mobile ApplicationTesthopstervenvlibsite-packagesdjangocoremanagement__init__.py”, line 381, in execute_from_command_line
utility.execute()

File “F:Python ProjectHopster Mobile ApplicationTesthopstervenvlibsite-packagesdjangocoremanagement__init__.py”, line 375, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)

File “F:Python ProjectHopster Mobile ApplicationTesthopstervenvlibsite-packagesdjangocoremanagementbase.py”, line 316, in run_from_argv
self.execute(*args, **cmd_options)

File “F:Python ProjectHopster Mobile ApplicationTesthopstervenvlibsite-packagesdjangocoremanagementcommandsrunserver.py”, line 60, in execute
super().execute(*args, **options)

File “F:Python ProjectHopster Mobile ApplicationTesthopstervenvlibsite-packagesdjangocoremanagementbase.py”, line 353, in execute
output = self.handle(*args, **options)

File “F:Python ProjectHopster Mobile ApplicationTesthopstervenvlibsite-packagesdjangocoremanagementcommandsrunserver.py”, line 67, in handle
if not settings.DEBUG and not settings.ALLOWED_HOSTS:

File “F:Python ProjectHopster Mobile ApplicationTesthopstervenvlibsite-packagesdjangoconf__init__.py”, line 57, in getattr
self._setup(name)

File “F:Python ProjectHopster Mobile ApplicationTesthopstervenvlibsite-packagesdjangoconf__init__.py”, line 44, in _setup
self._wrapped = Settings(settings_module)

File “F:Python ProjectHopster Mobile ApplicationTesthopstervenvlibsite-packagesdjangoconf__init__.py”, line 126, in init
raise ImproperlyConfigured(“The SECRET_KEY setting must not be empty.”)

django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty.

2

Answers


  1. I think the problem is in your manage.py. Your manage.py should be

    import locale
    import os
    import sys
    
    if __name__ == '__main__':
        locale.setlocale(locale.LC_ALL, '')
        os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'hopster.settings.local')    # Your local.py
    
        try:
            from django.core.management import execute_from_command_line
    
        except ImportError as exc:
            raise ImportError(
                'Could not import Django. Are you sure it is installed and '
                'available on your PYTHONPATH environment variable? Did you '
                'forget to activate a virtual environment?'
            ) from exc
    
        execute_from_command_line(sys.argv)
    
    Login or Signup to reply.
  2. Your manage.py file should be defined thus(as suitable for live deployment):

    import os
    import sys
    import dotenv #pip install python3-dotenv
    
    def main():
        """Run administrative tasks."""
        dotenv.load_dotenv(
            os.path.join(os.path.dirname(__file__), 'config.env')
        )
    
        os.environ.setdefault('DJANGO_SETTINGS_MODULE', "hopster.settings.local")
    
        if os.getenv("DJANGO_SETTINGS_MODULE"):
            os.environ["DJANGO_SETTINGS_MODULE"] = os.getenv("DJANGO_SETTINGS_MODULE")
    
        try:
            from django.core.management import execute_from_command_line
        except ImportError as exc:
            raise ImportError(
                "Couldn't import Django. Are you sure it's installed and "
                "available on your PYTHONPATH environment variable? Did you "
                "forget to activate a virtual environment?"
            ) from exc
        execute_from_command_line(sys.argv)
    
    
    if __name__ == '__main__':
        main()
    
    

    Then create a file (where your manage.py file is located) config.env and define the SECRET_KEY in that file. Furthermore, define the settings module. Your config.env file should looklike so:

    DJANGO_SETTINGS_MODULE = hopster.settings.local
    SECRET_KEY = tantallum@tungsten...(whatever)
    

    In your settings.local file, define your SECRET_KEY as:

    SECRET_KEY = os.getenv("SECRET_KEY")
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search