看了好多登录注册和注销的教程,很乱,很迷,然后总结了一下,简单的做了一个登录,注册和注销的页面。
1,首先,使用pycharm创建一个项目
单击File —> 选中Django —> 在右侧Location选中所需的路径,或直接在框里命名
2,现在,你有了一个Django项目
你需要单击左下方的Terminal
创建一个app,命令:python manage.py startapp Myapp(命名不做要求)
创建一个存放静态文件的文件夹:static(默认为该命名)
项目如下:
3,在Waste下:
settings.py:
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # 激活app 'Myapp' ] # 更改数据库连接 DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'HOST' : 'localhost', 'PORT' : 3306, 'NAME' : 'mysql', 'USER': 'root', 'PASSWORD' : '123456' } } # 汉语与时区 LANGUAGE_CODE = 'zh-hans' TIME_ZONE = 'Asia/Shanghai' # 静态文件夹路径 STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR,'static'), ]
在urls.py下:
from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), #更改url匹配,定向到myApp的urls中,当主机地址后面参数时,到myApp中找链接 path('',include('Myapp.urls')) ]
关闭这俩文件,因为我们基本用不到了。
4,在Myapp下:
新建urls.py,项目如下:
__init__.py:设置数据库连接
import pymysql pymysql.install_as_MySQLdb()
urls.py:
from django.urls import path from . import views urlpatterns = [ #主页,用来显示类别等其他数据 path('',views.index), # 登录 path('tologin/',views.tologin), # 注册 path('register/',views.register), # 注销 path('lagout/',views.lagout), ]
views.py:
from django.shortcuts import render, redirect from django.http import HttpResponseRedirect from django.contrib.auth.models import User from django.contrib.auth import authenticate,login,logout from django.contrib.auth.models import AnonymousUser # Create your views here. # 主页 def index(request,): username = request.user return render(request,'Myapp/index.html',locals()) # 登录 def tologin(request): if request.method == 'POST' and request.POST: data = request.POST username = data.get('username') password = data.get('password') n = authenticate(username=username,password=password) if n: # 登陆成功即可获取当前登录用户,返回主页 login(request,user=n) return redirect('/') # 失败重定向到登录页 return render(request, 'myApp/login.html') # 注册 def register(request): if request.method == 'POST' and request.POST: data = request.POST username = data.get("username") password = data.get("password") # 校验注册,名字不可重复 u = User.objects.filter(username=username).first() if u: info = '该用户名已被注册' return render(request,'Myapp/ERROR.html',{'info':info}) else: # 注册成功,创建用户 User.objects.create_user( username=username, password=password ) # 重定向到登录页面 return HttpResponseRedirect('/tologin/') # 注册失败,重新注册 return render(request,'Myapp/register.html') def lagout(request): logout(request) return redirect('/')