django from组件 实现增加 删除 编辑(推荐用法)
实现效果:
代码示例:
代码:
models.py
from django.db import models class UserInfo(models.Model): username = models.CharField(max_length=32) email = models.EmailField(max_length=32)
urls.py
from django.conf.urls import url from django.contrib import admin from app01 import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^users/', views.users), url(r'^add_user/', views.add_user), url(r'^edit_user-(\d+)/', views.edit_user), ]
views.py
from django.shortcuts import render from django.shortcuts import redirect from app01 import models from app01.forms import UserForm def users(request): user_list = models.UserInfo.objects.all() return render(request,'users.html',{'user_list':user_list}) def add_user(request): if request.method == 'GET': obj = UserForm() return render(request,'add_user.html',{'obj':obj}) else: obj = UserForm(request.POST) if obj.is_valid(): models.UserInfo.objects.create(**obj.cleaned_data) return redirect('/users/') else: return render(request,'add_user.html',{'obj':obj}) def edit_user(request,nid): if request.method == "GET": data = models.UserInfo.objects.filter(id=nid).first() obj = UserForm({'username':data.username,'email':data.email}) return render(request,'edit_user.html',{'obj':obj,'nid':nid}) else: obj = UserForm(request.POST) if obj.is_valid(): models.UserInfo.objects.filter(id=nid).update(**obj.cleaned_data) return redirect('/users/') else: return render(request,'edit_user.html',{'obj':obj,'nid':nid})
forms.py
from django import forms as dforms from django.forms import fields class UserForm(dforms.Form): username = fields.CharField() email = fields.EmailField()
users.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <a href="/add_user/">添加</a> <ul> {% for row in user_list %} <li>{{ row.id }}-{{ row.username }}-{{ row.email }} <a href="/edit_user-{{ row.id }}/">编辑</a></li> {% endfor %} </ul> </body> </html>
add_user.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/add_user/" method="post" novalidate> {% csrf_token %} <p>{{ obj.username }}{{ obj.errors.username.0 }}</p> <p>{{ obj.email }}{{ obj.errors.email.0 }}</p> <input type="submit" value="提交" /> </form> </body> </html>
edit_user.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/edit_user-{{ nid }}/" method="POST" novalidate> {% csrf_token %} <p>{{ obj.username }}{{ obj.errors.username.0 }}</p> <p>{{ obj.email }}{{ obj.errors.email.0 }}</p> <input type="submit" value="提交" /> </form> </body> </html>