建立了兩個satrtapp (app努酸,user)
app/urls.py
from django.urls import path, re_path
from app.views import *
urlpatterns = [
path('index/', index),
path('redirect_stu/', redirect_stu, name='red'),
path('redirect_params/<int:id>/', redirect_params, name='rep'),
re_path('redirect_prams_re/(\d+)/', redirect_params_re, name='rere'),
path('req/', req, name='req'),
path('res/', res, name='res'),
]
app/views.py
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
from django.urls import reverse
def index(request):
if request.method == 'GET':
# 跳轉(zhuǎn)到另外一個路由地址上
# 無參的情況下進(jìn)行跳轉(zhuǎn)
# 第一種跳轉(zhuǎn): 使用硬編碼url
# return HttpResponseRedirect('/app/redirect_stu/')
# print(reverse('a:red'))
# 第二種跳轉(zhuǎn): 使用反向解析 reverse('namespace:name')
# return HttpResponseRedirect(reverse('a:red'))
# 有參的情況下的跳轉(zhuǎn)
# return HttpResponseRedirect('/app/redirect_params/16/')
# return HttpResponseRedirect(reverse('a:rep', kwargs={'id': 18}))
# return HttpResponseRedirect(reverse('a:rere', args=(20,)))
return render(request, 'index.html')
def redirect_stu(request):
if request.method == 'GET':
return HttpResponse('我是跳轉(zhuǎn)過來的方法')
def redirect_params(request, id):
if request.method == 'GET':
return HttpResponse('帶參的跳轉(zhuǎn)窘行,參數(shù):%s' % id)
def redirect_params_re(request, id):
if request.method == 'GET':
return HttpResponse('帶參數(shù)的跳轉(zhuǎn)2, 參數(shù):%s' % id)
def req(request):
if request.method == 'GET':
# request.FILES 獲取文件
# request.path 獲取路由地址
# request.COOKIES 獲取cookie內(nèi)容
# request.session 獲取服務(wù)器中保存的session數(shù)據(jù)
# request.GET 獲取get請求傳遞的參數(shù)
# request.POST 獲取post請求傳遞的參數(shù)
return HttpResponse('請求')
def res(request):
if request.method == 'GET':
# return HttpResponse('響應(yīng)')
# return HttpResponseRedirect('跳轉(zhuǎn)')
# return render()
# return JsonResponse({'code':200})
response = HttpResponseRedirect('/app/index/')
response.set_cookie('token', 123456)
return response
day04/init.py(通常都視項目的名稱主路由和settings.py)
#版本的問題新的版本沒有mysqldb只能這樣初始化解決DID you pip install py----?
import pymysql
pymysql.install_as_MySQLdb()
day04/settings.py(設(shè)置賬號等配置文件路徑等)
"""
Django settings for day04 project.
Generated by 'django-admin startproject' using Django 2.1.7.
For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/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.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'a^^_drl%jp-tl1q6)i)!w*+cp(zvfg&xykw!zx9osur+jyduf9'
# 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',
'user',
]
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',
# 'utils.UserMiddleware.UserAuthMiddleware',
'utils.TestMiddleware.TestMiddle1',
'utils.TestMiddleware.TestMiddle2',
]
ROOT_URLCONF = 'day04.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 = 'day04.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'dj9_0',
'USER': 'root',
'PASSWORD': 'DENG5rong2hua0!',
'HOST':'127.0.0.1',
'PORT': 3306,
'OPTIONS': {'isolation_level':None}
}
}
# Password validation
# https://docs.djangoproject.com/en/2.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/2.1/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.1/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static')
]
# 沒登錄時,訪問地址
LOGIN_URL = '/user/login/'
# 媒體文件地址
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
day04/urls.py
"""day04 URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
from django.contrib.staticfiles.urls import static
from day04.settings import MEDIA_URL, MEDIA_ROOT
urlpatterns = [
path('admin/', admin.site.urls),
# 路由分發(fā)
path('user/', include(('user.urls', 'user'), namespace='user')),
# 定義namespace參數(shù)
path('app/', include(('app.urls', 'app'), namespace='a')),
]
# 配置訪問meida文件夾中的圖片數(shù)據(jù)
urlpatterns += static(MEDIA_URL, document_root=MEDIA_ROOT)
media是媒體文件放圖片F(xiàn)ILED等隘道。
templates/forms.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="" method="post" enctype="multipart/form-data">
<p>用戶名: <input type="text" name="username"> {{ errors.username }}</p>
<p>密碼: <input type="password" name="password"> {{ errors.password }}</p>
<p>確認(rèn)密碼: <input type="password" name="password2"> {{ errors.password2 }}</p>
<p>年齡:<input type="text" name="age"> {{ errors.age }}</p>
<p>頭像:<input type="file" name="icon"></p>
<p><input type="submit" value="提交"></p>
</form>
</body>
</html>
templates/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{{ user }}
<!-- namespase:name -->
<p><a href="{% url 'a:red' %}">無參跳轉(zhuǎn)</a></p>
<p><a href="{% url 'a:rep' 20 %}">有參跳轉(zhuǎn)1</a></p>
<p><a href="{% url 'a:rere' 20 %}">有參跳轉(zhuǎn)2</a></p>
<img src="/media/{{ users.2.icon }}">
</body>
</html>
templates/login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登錄</title>
</head>
<body>
{{ error }}
<form action="" method="post">
<p>姓名:<input type="text" name="username"></p>
<p>密碼:<input type="text" name="password"></p>
<p><input type="submit" value="提交"></p>
</form>
</body>
</html>
templates/register.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>注冊</title>
</head>
<body>
{{ error }}
<form action="" method="post">
<p>姓名:<input type="text" name="username"></p>
<p>密碼:<input type="text" name="password"></p>
<p>確認(rèn)密碼:<input type="text" name="password2"></p>
<p><input type="submit" value="提交"></p>
</form>
</body>
</html>
user/forms.py
from django import forms
from user.models import MyUser
class UserForm(forms.Form):
# 定義表單赌渣,驗證數(shù)據(jù)
username = forms.CharField(required=True, max_length=16, min_length=2,
error_messages={
'required': '必須填寫用戶名',
'max_length': '至多6字符',
'min_length': '至少2字符'
})
password = forms.CharField(required=True, max_length=6, min_length=3,
error_messages={
'required': '密碼不能為空',
'max_length' : '密碼不成超過6位',
'min_length': '密碼不能短于3位'
})
password2 = forms.CharField(required=True, max_length=6, min_length=3,
error_messages={
'required': '密碼不能為空',
'max_length' : '密碼不成超過6位',
'min_length': '密碼不能短于3位'
})
age = forms.IntegerField(required=False)
icon = forms.ImageField(required=False)
def clean(self):
# 用于校驗form表單的數(shù)據(jù),必須返回校驗字段后的結(jié)果
# 默認(rèn)調(diào)用
# 校驗密碼是否一致
pwd1 = self.cleaned_data.get('password')
pwd2 = self.cleaned_data.get('password2')
if pwd1 and pwd2:
if pwd1 != pwd2:
raise forms.ValidationError({'password2': '密碼和確認(rèn)密碼不一致'})
# self.cleaned_data['username'] = 'hahahhaha'
return self.cleaned_data
def clean_username(self):
# 注冊淮腾,校驗username是否存在
user = MyUser.objects.filter(username=self.cleaned_data.get('username')).first()
if user:
raise forms.ValidationError('該賬號已注冊糟需,請跟換賬號')
return self.cleaned_data['username']
# def clean_password(self):
# pass
#
# def clean_password2(self):
# pass
user/models.py
from django.db import models
class MyUser(models.Model):
username = models.CharField(max_length=10, unique=True, null=False)
password = models.CharField(max_length=255, null=False)
icon = models.ImageField(null=True, upload_to='upload')
class Meta:
db_table = 'my_user'
user/urls.py
from django.contrib.auth.decorators import login_required
from django.urls import path
from user.views import *
from utils.functions import is_login
urlpatterns = [
# django自帶的登錄注冊注銷的實現(xiàn)
path('register/', register, name='register'),
path('login/', login, name='login'),
path('index/', index, name='index'),
path('logout/', login_required(logout), name='logout'),
# 使用session實現(xiàn)登錄注銷功能
path('my_register/', my_register, name='my_register'),
path('my_login/', my_login, name='my_login'),
# session操作語法
path('sess/', sess_operate, name='sess_oprate'),
# 驗證頁面提交的表單數(shù)據(jù)
path('form_html/', form_html),
path('media_img/', media_img),
]
#user/views.py
from django.contrib.auth.hashers import make_password, check_password
from django.contrib.auth.models import User
from django.contrib import auth
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from user.forms import UserForm
from user.models import MyUser
def register(request):
if request.method == 'GET':
return render(request, 'register.html')
if request.method == 'POST':
# 獲取數(shù)據(jù)并校驗
username = request.POST.get('username')
password = request.POST.get('password')
password2 = request.POST.get('password2')
if username and password and password2 and password==password2:
if not User.objects.filter(username=username).exists():
# 保存
User.objects.create_user(username=username,
password=password)
return HttpResponseRedirect(reverse('user:login'))
error = '用戶已存在屉佳,請更換賬號'
return render(request, 'register.html', {'error': error})
else:
error = '注冊參數(shù)有誤,請確認(rèn)'
return render(request, 'register.html', {'error': error})
def login(request):
if request.method == 'GET':
return render(request, 'login.html')
if request.method == 'POST':
# 獲取數(shù)據(jù)
username = request.POST.get('username')
password = request.POST.get('password')
if username and password:
# 校驗
user = auth.authenticate(username=username,
password=password)
if user:
# 設(shè)置登錄狀態(tài)
# 查看session是否變化洲押,request.user這個東西的變化
auth.login(request, user)
# auth.logout(request)
return HttpResponseRedirect(reverse('user:index'))
error = '用戶名或者密碼錯誤'
return render(request, 'login.html', {'error': error})
else:
error = '登錄信息請?zhí)顚懲暾?
return render(request, 'login.html', {'error': error})
def index(request):
if request.method == 'GET':
print('index')
return render(request, 'index.html')
def logout(request):
if request.method == 'GET':
auth.logout(request)
return HttpResponseRedirect(reverse('user:login'))
def my_register(request):
if request.method == 'GET':
return render(request, 'register.html')
if request.method == 'POST':
# 獲取數(shù)據(jù)并校驗
username = request.POST.get('username')
password = request.POST.get('password')
password2 = request.POST.get('password2')
if username and password and password2 and password==password2:
if not MyUser.objects.filter(username=username).exists():
# 保存
pwd = make_password(password)
MyUser.objects.create(username=username,
password=pwd)
return HttpResponseRedirect(reverse('user:my_login'))
error = '用戶已存在武花,請更換賬號'
return render(request, 'register.html', {'error': error})
else:
error = '注冊參數(shù)有誤,請確認(rèn)'
return render(request, 'register.html', {'error': error})
def my_login(request):
if request.method == 'GET':
return render(request, 'login.html')
if request.method == 'POST':
# 獲取數(shù)據(jù)
username = request.POST.get('username')
password = request.POST.get('password')
if username and password:
# 校驗
user = MyUser.objects.filter(username=username).first()
if user:
if check_password(password, user.password):
# 登錄操作
request.session['user_id'] = user.id
return HttpResponseRedirect(reverse('user:index'))
error = '用戶名或者密碼錯誤'
return render(request, 'login.html', {'error': error})
else:
error = '登錄信息請?zhí)顚懲暾?
return render(request, 'login.html', {'error': error})
def sess_operate(request):
if request.method == 'GET':
# 取session_key的值
session_key = request.session.session_key
print(session_key)
# del request.session['user_id']
# request.session.delete(session_key)
request.session.flush()
return HttpResponse('操作session數(shù)據(jù)')
def form_html(request):
if request.method == 'GET':
return render(request, 'forms.html')
if request.method == 'POST':
# 定義表單诅诱,驗證頁面?zhèn)鬟f的參數(shù)
form = UserForm(request.POST, request.FILES)
if form.is_valid():
# 校驗成功
# form.cleaned_data 取值
icon = form.cleaned_data.get('icon')
# 保存圖片的位置髓堪, 保存數(shù)據(jù)庫my_user字段
MyUser.objects.create(username=form.cleaned_data['username'],
password=form.cleaned_data['password'],
icon=icon)
return HttpResponse('校驗成功')
errors = form.errors
return render(request, 'forms.html', {'errors': errors})
def media_img(request):
if request.method == 'GET':
users = MyUser.objects.all()
return render(request, 'index.html', {'users':users})
#utils/functions.py
from django.http import HttpResponseRedirect
from django.urls import reverse
from user.models import MyUser
def is_login(func):
def check(request):
# 登錄的校驗
if 'user_id' in request.session:
user = MyUser.objects.get(pk=request.session['user_id'])
request.user = user
return func(request)
else:
return HttpResponseRedirect(reverse('user:my_login'))
return check
#utils/TestMiddleware.py
from django.http import HttpResponse
from django.utils.deprecation import MiddlewareMixin
class TestMiddle1(MiddlewareMixin):
def process_request(self, request):
print('process_request1')
# return HttpResponse('1234567')
def process_response(self, request, response):
print('process_response1')
return response
# return HttpResponse('123456789')
def process_view(self, request, view_func, view_args, view_kwargs):
print('process_view1')
def process_exception(self, request, exception):
print('process_exception1')
class TestMiddle2(MiddlewareMixin):
def process_request(self, request):
print('process_request2')
# return HttpResponse('1234567')
def process_response(self, request, response):
print('process_response2')
return response
def process_view(self, request, view_func, view_args, view_kwargs):
print('process_view2')
def process_exception(self, request, exception):
print('process_exception2')
#utils/UserMiddleware.py
from django.http import HttpResponse
from django.utils.deprecation import MiddlewareMixin
class UserAuthMiddleware(MiddlewareMixin):
def process_request(self, request):
# 解析請求request來之后,直接執(zhí)行的娘荡。還沒匹配url
print('process_request')
# 登錄和注冊不需要做登錄校驗干旁,因此直接過濾掉請求url
path = request.path
if path in ['/user/my_login/', '/user/my_register/']:
return None
if 'user_id' in request.session:
# 表示不運行以下的所有代碼,直接去訪問路由文件炮沐,并執(zhí)行視圖函數(shù)
request.user = '1245678'
return None
return HttpResponse('我是中間件的process_request')