day04+05 Django實現(xiàn)簡單的登陸注冊數(shù)據(jù)校驗等功能

image.png

建立了兩個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')






最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末争群,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子大年,更是在濱河造成了極大的恐慌换薄,老刑警劉巖,帶你破解...
    沈念sama閱讀 219,039評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件翔试,死亡現(xiàn)場離奇詭異轻要,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)垦缅,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,426評論 3 395
  • 文/潘曉璐 我一進(jìn)店門冲泥,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人壁涎,你說我怎么就攤上這事凡恍。” “怎么了怔球?”我有些...
    開封第一講書人閱讀 165,417評論 0 356
  • 文/不壞的土叔 我叫張陵嚼酝,是天一觀的道長。 經(jīng)常有香客問我竟坛,道長闽巩,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,868評論 1 295
  • 正文 為了忘掉前任担汤,我火速辦了婚禮又官,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘漫试。我一直安慰自己六敬,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 67,892評論 6 392
  • 文/花漫 我一把揭開白布驾荣。 她就那樣靜靜地躺著外构,像睡著了一般普泡。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上审编,一...
    開封第一講書人閱讀 51,692評論 1 305
  • 那天撼班,我揣著相機(jī)與錄音,去河邊找鬼垒酬。 笑死砰嘁,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的勘究。 我是一名探鬼主播矮湘,決...
    沈念sama閱讀 40,416評論 3 419
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼口糕!你這毒婦竟也來了缅阳?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,326評論 0 276
  • 序言:老撾萬榮一對情侶失蹤景描,失蹤者是張志新(化名)和其女友劉穎十办,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體超棺,經(jīng)...
    沈念sama閱讀 45,782評論 1 316
  • 正文 獨居荒郊野嶺守林人離奇死亡向族,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,957評論 3 337
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了棠绘。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片件相。...
    茶點故事閱讀 40,102評論 1 350
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖弄唧,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情霍衫,我是刑警寧澤候引,帶...
    沈念sama閱讀 35,790評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站敦跌,受9級特大地震影響澄干,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜柠傍,卻給世界環(huán)境...
    茶點故事閱讀 41,442評論 3 331
  • 文/蒙蒙 一麸俘、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧惧笛,春花似錦从媚、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,996評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽喷众。三九已至,卻和暖如春紧憾,著一層夾襖步出監(jiān)牢的瞬間到千,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,113評論 1 272
  • 我被黑心中介騙來泰國打工赴穗, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留憔四,地道東北人。 一個月前我還...
    沈念sama閱讀 48,332評論 3 373
  • 正文 我出身青樓般眉,卻偏偏與公主長得像了赵,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子煤篙,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,044評論 2 355

推薦閱讀更多精彩內(nèi)容