使用Django框架完成用户的增删改查操作,需要按照以下步骤进行:
django-admin startproject projectname
其中projectname是你的项目名称。
python manage.py startapp appname
其中appname是你的应用名称。
配置数据库:
在项目的settings.py文件中设置数据库连接。默认使用的是SQLite数据库,你可以根据需要修改为其他数据库,比如MySQL。
创建用户模型:
在应用的models.py文件中定义用户模型,例如:
from django.db import models
class User(models.Model):
name = models.CharField(max_length=50)
email = models.EmailField()
age = models.IntegerField()
python manage.py makemigrations
python manage.py migrate
from django.shortcuts import render, get_object_or_404, redirect
from .models import User
def user_list(request):
users = User.objects.all()
return render(request, 'user_list.html', {'users': users})
def user_detail(request, pk):
user = get_object_or_404(User, pk=pk)
return render(request, 'user_detail.html', {'user': user})
def user_create(request):
if request.method == 'POST':
name = request.POST['name']
email = request.POST['email']
age = request.POST['age']
user = User.objects.create(name=name, email=email, age=age)
return redirect('user_detail', pk=user.pk)
return render(request, 'user_create.html')
def user_update(request, pk):
user = get_object_or_404(User, pk=pk)
if request.method == 'POST':
user.name = request.POST['name']
user.email = request.POST['email']
user.age = request.POST['age']
user.save()
return redirect('user_detail', pk=user.pk)
return render(request, 'user_update.html', {'user': user})
def user_delete(request, pk):
user = get_object_or_404(User, pk=pk)
user.delete()
return redirect('user_list')
{% for user in users %}
<p>{{ user.name }}p>
<p>{{ user.email }}p>
<p>{{ user.age }}p>
<a href="{% url 'user_detail' pk=user.pk %}">Detaila>
<a href="{% url 'user_update' pk=user.pk %}">Updatea>
<a href="{% url 'user_delete' pk=user.pk %}">Deletea>
{% endfor %}
user_detail.html:
<p>{{ user.name }}p>
<p>{{ user.email }}p>
<p>{{ user.age }}p>
<a href="{% url 'user_update' pk=user.pk %}">Updatea>
<a href="{% url 'user_delete' pk=user.pk %}">Deletea>
user_create.html:
<form method="post">
{% csrf_token %}
<input type="text" name="name">
<input type="email" name="email">
<input type="number" name="age">
<button type="submit">Createbutton>
form>
user_update.html:
<form method="post">
{% csrf_token %}
<input type="text" name="name" value="{{ user.name }}">
<input type="email" name="email" value="{{ user.email }}">
<input type="number" name="age" value="{{ user.age }}">
<button type="submit">Updatebutton>
form>
from django.urls import path
from . import views
urlpatterns = [
path('', views.user_list, name='user_list'),
path('create/', views.user_create, name='user_create'),
path('/' , views.user_detail, name='user_detail'),
path('/update/' , views.user_update, name='user_update'),
path('/delete/' , views.user_delete, name='user_delete'),
]
python manage.py runserver
现在你可以通过访问http://localhost:8000/来查看用户列表,并进行增删改查操作。