Django + mysql 实现登录、验证、更新功能
第一步:前期的配置
1.对项目的注册
在setting里面,进行新项目的注册
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'book.apps.BookConfig',
]
2.对静态文件的注册
在根目录的setting里
STATIC_URL = '/static/'
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),) # 添加静态文件
3.对接口的注册
在根目录的URL里面
from django.conf.urls import url
from django.contrib import admin
from book import views
urlpatterns = [
url('admin/', admin.site.urls),
url('login/', views.login), # 对登录的接口进行注册
url('register/', views.register), # 对注册的接口进行注册
]
4.在view.py里面定义接口函数的实现
实现登录、注册、和更新的操作
# view.py 里面导入http协议的包,导入model模型的user类,成功引入了表
from django.http import HttpResponse
# Create your views here.
from book.models import User
# 实现账号的登录功能
def login(request):
# select
# user = User(username='xm', password='123456')
# user.save()
# return HttpResponse('hehe')
username = request.GET.get('username')
password = request.GET.get('password')
result = '注册失败'
try:
user = User.objects.get(username = username)
if user:
if user.password == password:
return HttpResponse('登录成功')
else:
return HttpResponse('密码错误')
else:
return HttpResponse('账号不存在') # 账号不存在,无法显示出来
except:
pass
return HttpResponse('网络错误')
# 实现账号的注册功能
def register(request):
# 获取客户端通过get请求发送过来的数据
username = request.GET.get('username')
password = request.GET.get('password')
phone = request.GET.get('phone')
# insert into
# user = User(username ='xiaoming',password = '123456')
result = '注册失败'
#try:
user = User.objects.filter(username=username)
if user:
result = '用户已存在'
else:
User.objects.create(username=username, password=password)
result = '注册成功'
#except:
#pass
return HttpResponse(result)
# 实现账号更新的功能
def update(request):
# 获取客户端通过get请求发送过来的数据
uid= request.GET.get('uid')
password= request.GET.get('password')
result='高强傻逼'
try:
user = User.objects.filter(uid=uid)
User.objects.update(password=password)
result = '高强优秀'
except:
pass
return HttpResponse(result)
5.在model里面创建用户列表,并提供给views.py里面的接口使用
from django.db import models
# Create your models here.
class User(models.Model):
# 创建主键 创建username varchar
uid = models.AutoField(primary_key=True)
username = models.CharField(max_length=32)
password = models.CharField(max_length=32)
phone = models.CharField(max_length=11)
6.在static目录文件里面的HTML文件调用
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="http://127.0.0.1:8000/login" method="get"> # 此处静态文件调用接口,显示接口的功能
username:<input type="text" name="username"> # 接口改变,此处也需要改变
password:<input type="text" name="password">
<input type="submit">
</form>
</body>
</html>