赞
踩
之前我们用Django框架做了一个很简单的个人博客搭建,不论是页面还是功能都很粗糙
所以从这篇开始我打算做一个比较完整的【个人博客网站】,可能会分好几篇博客来讲述
等所有功能完善的差不多后,再考虑上传github
那本篇呢,我们主要实现博客的基础框架搭建,以及【登陆/注册/注销】功能的实现
我会顺便详细介绍一下小知识点,以及我踩的坑
简易版blog搭建:https://blog.csdn.net/Makasa/article/details/124982130?spm=1001.2014.3001.5502
环境:
import os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'hf&ss)e1pr49yngt1s9ql%7wgotm91vsvw&88$67@3p@hlm%^e' # 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.apps.UserConfig', ] 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', ] ROOT_URLCONF = 'MyBlog.urls' # 如果用户继承了AbstractUser,修改原生auth_user的模型的话就需要加这个配置 AUTH_USER_MODEL = 'user.UserProfile' 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', # 如果要在页面里面进行引用图片的话,就必须在这里添加配置 'django.template.context_processors.media' # 在模板中可以使用{ { MEDIA_URL}} ], }, }, ] WSGI_APPLICATION = 'MyBlog.wsgi.application' # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'blog', 'USER': 'root', 'PASSWORD': 'yy1998123', 'HOST': '127.0.0.1', 'PORT': '3306', } } # Password validation # https://docs.djangoproject.com/en/3.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/3.1/topics/i18n/ # 配置语言,时区 LANGUAGE_CODE = 'zh-hans' TIME_ZONE = 'Asia/Shanghai' USE_I18N = True USE_L10N = True USE_TZ = False # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.1/howto/static-files/ STATIC_URL = '/static/' # 配置静态文件夹路径 STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] # 配置媒体文件路径 MEDIA_URL = '' MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
from django.contrib import admin from django.urls import path, include from user.views import index """ 全局路径 """ urlpatterns = [ path('admin/', admin.site.urls), path('', index, name='index'), # 配置user路径 path('user/', include(('user.urls', 'user'), namespace='user')), # path('user/', include('user.urls', namespace='user')), ]
简单提及下:我们这里为什么要再单独在user应用下创建一个urls.py呢?
主要是为了让代码更加规范,一般情况下,项目比较大的话,我们肯定是有多个应用的,那各个应用的路径我们就统一配置在全局的urls中
单个应用底下的路由我们都配在一起,方便统一管理;
比如说:咱们这次做的登录注册功能,是与用户相关的,那我们就单独在user应用下新建一个urls.py,里面配置用户相关的操作,例:登录/注册/注销等…
"""
用户相关的路径
"""
from django.urls import path
from user.views import user_register, user_login, user_logout
urlpatterns = [
path('register', user_register, name='register'),
path('login', user_login, name='login'),
path('logout', user_logout, name='logout'),
]
from django.contrib.auth import logout from django.contrib.auth.hashers import make_password, check_password from django.db.models import Q from django.http import HttpResponse from django.shortcuts import render, redirect # Create your views here. from django.urls import reverse from user.forms import RegisterForm, LoginForm from user.models import UserProfile """ 视图函数 """ def index(request): """ 返回首页 :param request: :return: """ return render(request, "index.html") def user_register(request): """ 用户注册 :param request: :return: """ if request.method == 'GET': # 注意get一定要大写,不然无法将表单渲染在页面上 return render(request, 'user/register.html') else: rform = RegisterForm(request.POST) # 使用form获取数据 print('--------》', rform) print("errors", rform.errors) if rform.is_valid(): # 进行数据的校验 # 从干净的数据中取值,即通过前端校验的数据 username = rform.cleaned_data.get('username') email = rform.cleaned_data.get('email') mobile = rform.cleaned_data.get('mobile') password = rform.cleaned_data.get('password') # 如果用户名/手机号不存在的话,才进行添加数据操作 if not UserProfile.objects.filter(Q(username=username) | Q(mobile=mobile)).exists(): # 注册到数据库中 password = make_password(password) # 密码进行加密 user = UserProfile.objects.create(username=username, password=password, email=email, mobile=mobile) if user: # 如果用户创建成功,则提示注册成功 return HttpResponse('注册成功') else: # 否则用户名/手机号已存在 return render(request, 'user/register.html', context={ 'msg': '用户名或者手机号已经存在!'}) # 数据校验失败,就提示注册失败 return render(request, 'user/register.html', context={ 'msg': '用户名或者手机号已经存在,请重新填写!'}) def user_login(request): """ 用户登陆 :param request: :return: """ if request.method == 'GET': return render(request, 'user/login.html') else: lform = LoginForm(request.POST) print('--------》', lform) print("errors", lform.errors) if lform.is_valid(): username = lform.cleaned_data.get('username') password = lform.cleaned_data.get('password') # 查询数据库,如果加密后的两个密码一致的话登录成功 user = UserProfile.objects.filter(username=username).first() flag = check_password(password
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。