使用Django框架完成用户的增删改查操作
以下是一个简单的Django框架示例,展示了如何实现用户的增删改查操作:
首先,确保你已经安装了Django。
- 创建一个新的Django项目和应用:
django-admin startproject myproject
cd myproject
python manage.py startapp users
- 编辑
users/models.py
来定义用户模型:
from django.db import models
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
is_active = models.BooleanField(default=True)
- 更新
settings.py
来使用自定义的用户模型:
# settings.py
AUTH_USER_MODEL = 'users.User'
- 创建数据库迁移:
python manage.py makemigrations
python manage.py migrate
- 在
users/views.py
中编写视图函数来处理CRUD操作:
from django.shortcuts import render, redirect
from django.contrib import messages
from django.contrib.auth.models import User
from django.contrib.auth import update_session_auth_hash
# 创建用户
def create_user(request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
user = User.objects.create_user(username=username, password=password)
user.save()
messages.success(request, 'User created successfully')
return redirect('users:list_users')
return render(request, 'users/create_user.html')
# 删除用户
def delete_user(request, pk):
user = User.objects.get(pk=pk)
user.delete()
messages.success(request, 'User deleted successfully')
return redirect('users:list_users')
# 更新用户
def update_user(request, pk):
user = User.objects.get(pk=pk)
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
user.username = username
user.set_password(password)
user.save()
messages.success(request, 'User updated successfully')
return redirect('users:list_use
评论已关闭