Dmitri-Sintsov / django-jinja-knockout

Django datatables and widgets, both AJAX and traditional. Display-only ModelForms. ModelForms / inline formsets with AJAX submit and validation. Works with Django templates.
https://django-jinja-knockout.readthedocs.org/
Other
144 stars 29 forks source link

Please Help - Middleware Error #6

Closed tusharcoder closed 6 years ago

tusharcoder commented 6 years ago

Error related to middleware

DJK_MIDDLEWARE

TypeError: init() takes 1 positional argument but 2 were given

Unhandled exception in thread started by <_pydev_bundle.pydev_monkey._NewThreadStartupWithTrace object at 0x10c636940>
Traceback (most recent call last):
  File "/Applications/PyCharm.app/Contents/helpers/pydev/_pydev_bundle/pydev_monkey.py", line 589, in __call__
    return self.original_func(*self.args, **self.kwargs)
  File "/Users/Tushar/workspace/hcl/venv/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper
    fn(*args, **kwargs)
  File "/Users/Tushar/workspace/hcl/venv/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 140, in inner_run
    handler = self.get_handler(*args, **options)
  File "/Users/Tushar/workspace/hcl/venv/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/runserver.py", line 27, in get_handler
    handler = super().get_handler(*args, **options)
  File "/Users/Tushar/workspace/hcl/venv/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 65, in get_handler
    return get_internal_wsgi_application()
  File "/Users/Tushar/workspace/hcl/venv/lib/python3.6/site-packages/django/core/servers/basehttp.py", line 44, in get_internal_wsgi_application
    return import_string(app_path)
  File "/Users/Tushar/workspace/hcl/venv/lib/python3.6/site-packages/django/utils/module_loading.py", line 17, in import_string
    module = import_module(module_path)
  File "/Users/Tushar/workspace/hcl/venv/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 "/Users/Tushar/workspace/hcl/hcl/hcl/wsgi.py", line 16, in <module>
    application = get_wsgi_application()
  File "/Users/Tushar/workspace/hcl/venv/lib/python3.6/site-packages/django/core/wsgi.py", line 13, in get_wsgi_application
    return WSGIHandler()
  File "/Users/Tushar/workspace/hcl/venv/lib/python3.6/site-packages/django/core/handlers/wsgi.py", line 140, in __init__
    self.load_middleware()
  File "/Users/Tushar/workspace/hcl/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 39, in load_middleware
    mw_instance = middleware(handler)
TypeError: __init__() takes 1 positional argument but 2 were given

My Settings.py

"""
Django settings for hcl project.

Generated by 'django-admin startproject' using Django 2.0.

For more information on this file, see
https://docs.djangoproject.com/en/2.0/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.0/ref/settings/
"""

import os
import random
from distutils.version import LooseVersion

import environ
from django import get_version
from django.utils import timezone

root = environ.Path(__file__) - 0  # three folder back (/a/b/c/ - 3 = /)
get_env_variable = environ.Env(DEBUG=(bool, False), )
environ.Env.read_env()

# 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/2.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = get_env_variable('SECRET_KEY')

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

ALLOWED_HOSTS = []

# Application definition
JS_ERRORS_ALERT = DEBUG
# Requires proper setup of Django email error logging.
JS_ERRORS_LOGGING = not DEBUG

DJK_APPS = (
    'hcl',
    'models_',
    'event_app',
)

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.sites',
    'django_jinja',
    'django_jinja.contrib._humanize',
    'django_jinja_knockout',
    'django_jinja_knockout._allauth',
    )+DJK_APPS+(
    'allauth',
    'allauth.account',
    # Required for socialaccount template tag library despite we do not use social login
    'allauth.socialaccount'
)

DJK_MIDDLEWARE = 'hcl.middleware.ContextMiddleware'

MIDDLEWARE = [
    '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',
    'django.middleware.security.SecurityMiddleware',
]

if LooseVersion(get_version()) >= LooseVersion('1.11'):
    MIDDLEWARE.append(DJK_MIDDLEWARE)
else:
    MIDDLEWARE_CLASSES = MIDDLEWARE
    MIDDLEWARE.extend([
        'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
        DJK_MIDDLEWARE,
    ])
AUTHENTICATION_BACKENDS = (
    # Needed to login by username in Django admin, regardless of `allauth`
    'django.contrib.auth.backends.ModelBackend',
    # `allauth` specific authentication methods, such as login by e-mail
    'allauth.account.auth_backends.AuthenticationBackend',
)

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'filters': {
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse',
        }
    },
    'handlers': {
        'file': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'filename': os.path.join(BASE_DIR, 'logs', 'django_log.sql'),
        },
        'mail_admins': {
            'level': 'ERROR',
            'filters': ['require_debug_false'],
            'class': 'django.utils.log.AdminEmailHandler',
            'include_html': True,
        }
    },
    'loggers': {
        'django': {
            'handlers': ['file', 'mail_admins'],
            'level': 'DEBUG',
            'propagate': True,
        },
    },
}

ROOT_URLCONF = 'hcl.urls'

try:
    # Django > 1.9
    from django.template.context_processors import i18n
    i18n_processor = 'django.template.context_processors.i18n'
except ImportError:
    from django.core.context_processors import i18n
    i18n_processor = 'django.core.context_processors.i18n'

TEMPLATES = [
    {
        "BACKEND": "django_jinja.backend.Jinja2",
        "APP_DIRS": True,
        "OPTIONS": {
            "match_extension": ".htm",
            "app_dirname": "jinja2",
            'context_processors': [
                i18n_processor,
                # For simple cases it is enough to include original template context processor (commented out).
                'hcl.context_processors.template_context_processor'
                # 'django_jinja_knockout.context_processors.template_context_processor'
            ]
        },
    },
    {
        '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',
                # Next line is required only if project uses Django templates (DTL).
                'hcl.context_processors.template_context_processor'
            ],
        },
    },
]

WSGI_APPLICATION = 'hcl.wsgi.application'

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

DATABASES = {
    'default': get_env_variable.db(),
    'sqllite': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    },
'TEST': {
            'NAME': ':memory:',
            # 'NAME': os.path.join(BASE_DIR, 'test.sqlite3'),
        },
}

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

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

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

STATIC_URL = '/static/'

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

# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
    # 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)

# Next setting is required so multiple Django instances running at the same host/IP with different ports
# do not interfere each other (apollo13).
SESSION_COOKIE_NAME = 'djk_sessionid'

# As this is the test application, registration with SMTP confirmation is not supported.
# Use:
""" python manage.py createsuperuser """
# or:
"""
python manage.py shell
from django.contrib.auth.models import User
user = User.objects.create_user('user', email='user@gmail.com', password='test123')
user.save()
exit()
"""

# For 'allauth'.
SITE_ID = 1
# Prevents infinite redirect when user has no permission to access current view.
ACCOUNT_AUTHENTICATED_LOGIN_REDIRECTS = False
ALLAUTH_DJK_URLS = True

# Login / logout for allauth.
LOGIN_URL = '/accounts/login/'
LOGIN_REDIRECT_URL = "/"
LOGOUT_URL = '/accounts/logout/'

# Pagination settings.
OBJECTS_PER_PAGE = 3 if DEBUG else 10

# unit testing settings
FIXTURE_DIRS = (
    os.path.join(BASE_DIR, 'fixtures'),
)

random.seed(timezone.now().timestamp())

Please help what am I missing ??

Dmitri-Sintsov commented 6 years ago

Does it work with non-extended (standard) middleware?

# DJK_MIDDLEWARE = 'hcl.middleware.ContextMiddleware'
DJK_MIDDLEWARE = 'django_jinja_knockout.middleware.ContextMiddleware'

Do you really need to extend built-in djk middleware? See an example of extended middlware at https://github.com/Dmitri-Sintsov/djk-sample/blob/master/djk_sample/middleware.py

I also have an private project with much more large extended djk middleware that works (in Django 1.11).

Locally the tests passed with Django 2.0.

tusharcoder commented 6 years ago

I just used the default 'django_jinja_knockout.middleware.ContextMiddleware'

It also didn't work with the extended Middleware that I made( DJK_MIDDLEWARE = 'hcl.middleware.ContextMiddleware) that I commented out But If I didn't apply any Middleware then there is no error.

Dmitri-Sintsov commented 6 years ago

I figured out why you are getting this error in Django 2.0. Only git master of django-jinja-knockout 0.7.0 which is unreleased to pypi yet is Django 2.0 compatible. pypi has only 0.6.0 version, which produces the same error in my test app. Please try to use git master version until 0.7.0 is released at pypi:

python -m pip install git+https://github.com/Dmitri-Sintsov/django-jinja-knockout.git

Or wait unitil I build-up and finish version 0,7,0 release and upload it to pypi, so it will be possible to use pypi fixed version. I will inform you about the release via the message in this thread.

Sorry for the inconvenience!

Dmitri-Sintsov commented 6 years ago

Version 0.7.1 is released: https://pypi.python.org/pypi?:action=display&name=django-jinja-knockout&version=0.7.1

So, Django 2.0 is supported "out of box" now with normal installation from pypi:

python3 -m pip install django-jinja-knockout