django和layui和mysql写一个注册登录代码
时间: 2024-06-08 08:12:18 浏览: 189
好的,下面是一个简单的 Django + layui + MySQL 实现的注册登录代码示例。
首先,需要安装 Django 和 pymysql 库,可以使用以下命令进行安装:
```
pip install Django pymysql
```
接下来,创建一个 Django 项目和一个应用程序:
```
django-admin startproject myproject
cd myproject
python manage.py startapp myapp
```
然后,打开 myproject/settings.py 文件,在 INSTALLED_APPS 中添加 myapp:
```python
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp', # 添加应用程序
]
```
接着,打开 myproject/settings.py 文件,在 DATABASES 中添加 MySQL 数据库的配置:
```python
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'mydatabase',
'USER': 'myuser',
'PASSWORD': 'mypassword',
'HOST': 'localhost',
'PORT': '3306',
}
}
```
其中,mydatabase、myuser、mypassword 分别为 MySQL 数据库的名字、用户名和密码,localhost 和 3306 分别为 MySQL 数据库的地址和端口。
现在,打开 myapp/models.py 文件,定义一个 User 模型:
```python
from django.db import models
class User(models.Model):
username = models.CharField(max_length=20, unique=True)
password = models.CharField(max_length=20)
email = models.EmailField(unique=True)
phone = models.CharField(max_length=11, unique=True)
```
然后,运行以下命令来创建 User 模型所对应的数据库表:
```
python manage.py makemigrations
python manage.py migrate
```
接下来,打开 myapp/views.py 文件,实现注册和登录功能:
```python
from django.shortcuts import render, redirect
from django.contrib import messages
from .models import User
import hashlib
def register(request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
email = request.POST['email']
phone = request.POST['phone']
if User.objects.filter(username=username).exists():
messages.error(request, 'Username is already taken.')
return redirect('register')
if User.objects.filter(email=email).exists():
messages.error(request, 'Email is already taken.')
return redirect('register')
if User.objects.filter(phone=phone).exists():
messages.error(request, 'Phone number is already taken.')
return redirect('register')
user = User(username=username, password=hashlib.sha256(password.encode('utf-8')).hexdigest(), email=email, phone=phone)
user.save()
messages.success(request, 'You are now registered and can log in.')
return redirect('login')
return render(request, 'register.html')
def login(request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
user = User.objects.filter(username=username, password=hashlib.sha256(password.encode('utf-8')).hexdigest()).first()
if user:
messages.success(request, 'You are now logged in.')
request.session['user_id'] = user.id
return redirect('home')
else:
messages.error(request, 'Invalid username or password.')
return redirect('login')
return render(request, 'login.html')
def home(request):
user_id = request.session.get('user_id')
if user_id:
user = User.objects.get(id=user_id)
return render(request, 'home.html', {'user': user})
else:
return redirect('login')
```
在上述代码中,register() 函数实现了注册功能,当用户提交表单时,它会检查用户名、邮箱和手机号是否已经存在,如果存在就返回错误信息,如果不存在就创建一个新用户并保存到数据库中。login() 函数实现了登录功能,当用户提交表单时,它会检查用户名和密码是否正确,如果正确就将用户的 id 存储在 session 中,并跳转到主页。home() 函数实现了主页功能,它会检查用户是否已经登录,如果已经登录就显示用户的信息,否则就跳转到登录页面。
接下来,创建 myapp/templates 目录,然后在该目录下创建 register.html、login.html 和 home.html 三个模板文件:
register.html:
```html
{% extends 'base.html' %}
{% block content %}
<div class="layui-container">
<div class="layui-row">
<div class="layui-col-md6 layui-col-md-offset3">
<form class="layui-form" action="{% url 'register' %}" method="post">
{% csrf_token %}
<div class="layui-form-item">
<label class="layui-form-label">Username</label>
<div class="layui-input-block">
<input type="text" name="username" required lay-verify="required" placeholder="Enter username" autocomplete="off" class="layui-input">
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">Password</label>
<div class="layui-input-block">
<input type="password" name="password" required lay-verify="required" placeholder="Enter password" autocomplete="off" class="layui-input">
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">Email</label>
<div class="layui-input-block">
<input type="email" name="email" required lay-verify="required|email" placeholder="Enter email" autocomplete="off" class="layui-input">
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">Phone</label>
<div class="layui-input-block">
<input type="tel" name="phone" required lay-verify="required|phone" placeholder="Enter phone number" autocomplete="off" class="layui-input">
</div>
</div>
<div class="layui-form-item">
<div class="layui-input-block">
<button class="layui-btn" lay-submit lay-filter="register">Register</button>
</div>
</div>
</form>
</div>
</div>
</div>
{% endblock %}
```
login.html:
```html
{% extends 'base.html' %}
{% block content %}
<div class="layui-container">
<div class="layui-row">
<div class="layui-col-md6 layui-col-md-offset3">
<form class="layui-form" action="{% url 'login' %}" method="post">
{% csrf_token %}
<div class="layui-form-item">
<label class="layui-form-label">Username</label>
<div class="layui-input-block">
<input type="text" name="username" required lay-verify="required" placeholder="Enter username" autocomplete="off" class="layui-input">
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">Password</label>
<div class="layui-input-block">
<input type="password" name="password" required lay-verify="required" placeholder="Enter password" autocomplete="off" class="layui-input">
</div>
</div>
<div class="layui-form-item">
<div class="layui-input-block">
<button class="layui-btn" lay-submit lay-filter="login">Login</button>
</div>
</div>
</form>
</div>
</div>
</div>
{% endblock %}
```
home.html:
```html
{% extends 'base.html' %}
{% block content %}
<div class="layui-container">
<div class="layui-row">
<div class="layui-col-md6 layui-col-md-offset3">
<div class="layui-card">
<div class="layui-card-header">User Information</div>
<div class="layui-card-body">
<p>Username: {{ user.username }}</p>
<p>Email: {{ user.email }}</p>
<p>Phone: {{ user.phone }}</p>
</div>
</div>
</div>
</div>
</div>
{% endblock %}
```
最后,创建 myapp/templates/base.html 文件,它是所有模板文件的基础模板:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>{% block title %}My Site{% endblock %}</title>
<link rel="stylesheet" href="https://cdn.staticfile.org/layui/2.5.6/css/layui.min.css">
<script src="https://cdn.staticfile.org/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdn.staticfile.org/layui/2.5.6/layui.min.js"></script>
</head>
<body>
{% block content %}{% endblock %}
</body>
</html>
```
现在,运行以下命令来启动 Django 服务器:
```
python manage.py runserver
```
然后,在浏览器中访问 http://localhost:8000/register,就可以看到注册页面了。注册完成后,就可以登录并查看个人信息了。
阅读全文