-
@ $效果图:
-
所修改目录:
-
app01目录下修改:
views.py:
from django.shortcuts import render,HttpResponse,redirect
def login(request):
# 判断用户获取数据方式是GET,就返回什么数据
if request.method == "GET":
return render(request, 'login.html')
# 判断用户获取数据方式是POST,就判断用户提交的数据是否正确
elif request.method == "POST":
# 数据表中执行 select * from user where username='x' and password='x'
u = request.POST.get('user')
p = request.POST.get('pwd')
obj = models.UserInfo.objects.filter(username=u,password=p).first()
# print(obj) obj->None(就是没有这个用户)
if obj:
return redirect('/cmdb/index/')
else:
return render(request, 'login.html')
else:
# PUT,DELETE,HEAD,OPTION...
return redirect("/index/")
def index(request):
return render(request, 'index.html')
def user_info(request):
user_list = models.UserInfo.objects.all()
# print(user_list.query)
# QuerySet [obj,obj,]
return render(request, 'user_info.html', {'user_list':user_list})
def user_detail(request,nid):
obj = models.UserInfo.objects.filter(id=nid).first()
# 取单条数据,如果不存在,直接报错(不推荐)
# models.UserInfo.objects.get(id=nid)
return render(request, 'user_detail.html',{'obj':obj})
from app01 import models
def orm(request):
# 创建 操作数据操作表(推荐)*****************
# models.UserInfo.objects.create(username='root',password='123')
# 效果同上
# dic = {'username': 'eric', 'password':'666'}
# models.UserInfo.objects.create(**dic)
# 效果(作用)同上
# obj = models.UserInfo(username='root',password='123')
# obj.save()
# 查 ******************
# result = models.UserInfo.objects.all()
# filter查找哪一个
# result = models.UserInfo.objects.filter(username='root')
# result,QuerySet => Django => []
# [obj(id,username,password), obj(id,username,password), obj(id,username,password)]
# for row in result:
# print(row.id,row.username,row.password)
# print(result)
# 删除*********************all(), filter()
# models.UserInfo.objects.filter(username="root").delete()
# 更新**********************update(),all(), filter()
models.UserInfo.objects.filter(id=3).update(password='889')
return HttpResponse('orm')
from django.views import View
class Home(View):
# 调用父类中的dispatch(相当于助理,)
def dispatch(self, request, *args, **kwargs):
print('before')
result = super(Home,self).dispatch(request, *args, **kwargs)
print('after')
return result
def get(self,request):
print(request.method)
return render(request, 'home.html')
def post(self,request):
print(request.method, 'POST')
return render(request, 'home.html')
- urls.py:
from django.conf.urls import url,include
from django.contrib import admin
from app01 import views
urlpatterns = [
url(r'^login/', views.login),
url(r'^index/', views.index),
url(r'^user_info/', views.user_info),
url(r'^userdetail-(?P\d+)/', views.user_detail),
url(r'orm/', views.orm),
]
-
templates目录修改:
- user_detail.html:
Title
Guido(Python之父,仁慈的独裁者)
- user_info.html:
Title
Guido(Python之父,仁慈的独裁者)
用户列表
{% for row in user_list %}
- {{row.username}}
{% endfor %}
- index.html:
Title
Guido(Python之父,仁慈的独裁者)
- login.html:
Title
-
运行django,浏览器访问
(http://127.0.0.1:8000/cmdb/userdetail-1/)
(http://127.0.0.1:8000/cmdb/user_info/)