尝试在Django

时间:2018-05-14 11:08:12

标签: python django django-middleware

settings.py

"""
Django settings for tutorial project.

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

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

# 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 = 'tw)pqpbi)r_z1lr0j#h1m6m)wy*8b+4-iorw#%-t3#x)6wuv8$'

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

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'accounts',

    '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',
    'tutorial.middleware.LoginRequiredMiddleware'
]

ROOT_URLCONF = 'tutorial.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 = 'tutorial.wsgi.application'


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

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.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/2.0/howto/static-files/

STATIC_URL = '/static/'

LOGIN_REDIRECT_URL = '/account/'



EMAIL_HOST = 'localhost'
EMAIL_PORT = 1025

LOGIN_EXEMPT_URLS = (
    r'^accounts/logout/$',
    r'^accounts/register/$',

)

urls.py

from django.contrib import admin
from django.conf.urls import url,include
from tutorial import views
#from django.urls import path

urlpatterns = [
    url('admin/', admin.site.urls),
    url('accounts/',include('accounts.urls')),
    url(r'^$',views.login_redirect,name="login_redirect"),
]

middleware.py

from django.conf import settings
from django.shortcuts import redirect
import re

EXEMPT_URLS = [re.compile(settings.LOGIN_URL.lstrip('/'))]
if hasattr(settings, 'LOGIN_EXEMPT_URLS'):
    EXEMPT_URLS +=[re.compile(url) for url in settings.LOGIN_EXEMPT_URLS]

class LoginRequiredMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response
    def __call__(self,request):
        response = self.get_response
        return redirect
    def process_view (self, request, view_func, view_args, view_kwargs):
        assert hasattr(request, 'user')
        path = request.path_info.lstrip('/')

        if not user.is_authenticated():
            if not any(url.match(path) for url in EXEMPT_URLS):
                return redirec(settings.LOGIN_URL)

和views.py

from django.shortcuts import render,redirect
from django.http import HttpResponse
from django.contrib.auth.forms import UserCreationForm
from tutorial import views
from accounts.form import Registrationform,EditProfileForm
from django.contrib.auth.forms import UserChangeForm,PasswordChangeForm
from django.contrib.auth.models import User
from django.contrib.auth import update_session_auth_hash
from django.contrib.auth.decorators import login_required

# Create your views here.
@login_required
def home(request):
    numbers=[1,2,3,4,5]
    name="jay"
    args={'myName':name}

    return render(request,'accounts/home.html',args)
def register(request):
    if request.method == "POST":
        form = Registrationform(request.POST)
        if form.is_valid():
            form.save()
            return redirect('/accounts')
        else:
            return HttpResponse('please fill all the fields and make sure new password must be match')
    else:
        form = Registrationform()
        args={'form' : form}
        return render(request,'accounts/reg_form.html',args)
@login_required
def view_profile(request):
    args = {'user' : request.user}
    return render(request,'accounts/profile.html',args)
@login_required
def edit_profile(request):
    if request.user.is_authenticated():
        #<p>Welcome, {{ user.username }}. Thanks for logging in.</p>
        if request.method=="POST":
            form = EditProfileForm(request.POST,instance=request.user)
            if form.is_valid():
                form.save()
                return redirect('/accounts/profile')
            else:
                return HttpResponse("please go back and write correct vaues")
        else:
            form  =  EditProfileForm(instance=request.user)
            args = {'form' : form}
            return render(request,'accounts/edit_profile.html',args)
    else:
        HttpResponse("hllo")
        return redirect('/accounts/login')
@login_required
def change_password(request):
    if request.user.is_authenticated():
        if request.method == "POST":
            form = PasswordChangeForm(data=request.POST,user=request.user)
            if form.is_valid():
                form.save()
                update_session_auth_hash(request, form.user)
                return redirect('/accounts/profile')
            else:
                return HttpResponse("password does not match,go back and try again")
        else:
            form = PasswordChangeForm(user=request.user)
            args = {'form' : form}
            return render(request,'accounts/change_password.html',args)
    else:
        return redirect ('/accounts/login')

当我转到网址http://127.0.0.1:8000/accounts/时,会出现如下错误:

A server error occurred.  Please contact the administrator.

我发现当我从'tutorial.middleware.LoginRequiredMiddleware'删除MIDDLEWARE_CLASSES时,它可以正常工作但添加后无效。我还尝试将MIDDLEWARE_CLASSES更改为MIDDLEWARE,但之后它给了我一个错误,如

WSGIRequest' object has no attribute 'user.

我删除了MIDDLEWARE_CLASSES然后它无效 终端显示:

Performing system checks...

System check identified no issues (0 silenced).
May 14, 2018 - 05:49:00
Django version 1.9, using settings 'tutorial.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
Internal Server Error: /accounts/
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 149, in get_response
    response = self.process_exception_by_middleware(e, request)
  File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 147, in get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/decorators.py", line 22, in _wrapped_view
    if test_func(request.user):
AttributeError: 'WSGIRequest' object has no attribute 'user'

我该怎么做才能解决这个问题?

1 个答案:

答案 0 :(得分:2)

您的settings.py(使用Django 2.0.2生成)和您的日志(Django版本1.9)之间似乎不匹配。

您的LoginRequiredMiddleware看起来像新式中间件(需要Django 1.10+),因此您应该使用MIDDLEWARE设置而不是MIDDLEWARE_CLASSES。改为使用最新的2.0.x版本运行服务器。

如果你无法升级到Python 3和Django 2.0,那么你应该使用MIDDLEWARE_CLASSES代替MIDDLEWARE和Django&lt; 1.10。不过,您的LoginRequiredMiddleware专为新款MIDDLEWARE设计,不适用于MIDDLEWARE_CLASSES

最后,请注意Django 1.10及更早版本不受支持且不接受安全修复,因此您应该尝试至少使用Django 1.11 LTS。