项目及app
新建项目admin-django startproject web_login
新建app python manage.py startapp app01
setting配置
1.配置terminal(pycharm专业版可忽略)
'DIRS': [os.path.join(BASE_DIR,'templates')]
2.注册app(将app01加载最后,注意逗号)
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'app01',
]
3
数据库类生成
class User_inf(models.Model):
user=models.CharField(max_length=20,unique=True)
pwd=models.CharField(max_length=20)
url分发
from django.contrib import admin
from django.urls import path
from app01.views import *
urlpatterns = [
path('admin/', admin.site.urls),
path('login/', login),
path('index/', index),
]
view函数(发送session及数据库查询)
def login(request):
if request.method=='POST':
user=request.POST.get('user')
pwd=request.POST.get('pwd')
if User_inf.objects.filter(user=user)[0].pwd==pwd:
request.session['user_pwd']=user+pwd
return redirect('/index/')
else:
return HttpResponse('密码错误')
return render(request,'login.html')
def index(request):
if request.session.get('user_pwd',None):
return render(request,'index.html')
else:
return redirect('/login/')
html文件
1.login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登录注册</title>
<style type="text/css">
#a{margin-bottom: 20px;border: 20px rgb(155,155,155) solid;width: 250px;height: auto;background-color: rgba(164, 255, 8, 0.4);padding: 20px;
}
.up{margin-bottom: 20px;width: 250px}
</style>
</head>
<body>
<div id="a">login
<div id="01">
<form id="011" method="post" action="/login/">
<p class="up">账号<input type="text" name="user" ></p>
<p class="up">密码<input type="password" name="pwd"></p>
<p class="up"><input type="submit" value="提交"></p>
</form>
</div>
</div>
</body>
</html>
2.index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>'login sucess!'</h1>
</body>
</html>
终端启动终止服务
数据库生成:
python manage.py makemigirations
python manage.py migrate
启动服务:
python manage.py runserver ip:端口号
终止服务:
CTRL+BREAK
其他(账号注册)
注册功能省略,大致思路:判断数据库是否有该账号,没有则添加,并判断密码是否一致。大致思路见下方。
def register(request):
user=request.POST.get('user')
pwd1=request.POST.get('pwd1')
pwd2=request.POST.get('pwd2')
if User_inf.objects.filter(name='user'):
return HttpResponse('该账号已经注册')
else:
if pwd1==pwd2:
User_inf.objects.create(name=user,pwd=pwd1)
return HttpResponse('注册成功')
else:
return HttpResponse('账号不一致')
来源:CSDN
作者:psxhh
链接:https://blog.csdn.net/psxhh/article/details/104214556