1增删改查步骤
(第一步)配置项目里的urls.py文件
from django.conf.urls import include,url
from django.contrib import admin
urlpatterns=[
url(r'^admin/', include(admin.site.urls)),-------include()表示你接下来的路径
#url(r'^depart/',include('company.urls',namespace='company')),
url(r'^com/',include('company.urls',namespace='com')),----- 我要进入app为company里的urls
url(r'^user/',include('uuser.urls',namespace='user')),
]
(二)接下来配置app里的urls.py文件 前面是匹配正则,后面是调用views.py文件里的方法
from django.conf.urls import include,url
from django.contrib import admin
from . import views
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^companyA/$',views.departall,name='departall'),
url(r'^company/add/$',views.depart_add,name='depart_add')
url(r'^company/add_list$',views.departNewAdd,name='departNewAdd'),
url(r'^company/delete$',views.depart_delete,name='depart_delete'),
url(r'^company/update$',views.depart_update,name='depart_update'),
url(r'^company/update_handler$',views.depart_update_handler,name='depart_update_handler'),
(三)配置app里的views.py文件 (增)
#导入模块
from django.shortcuts import render
from django.http import *
from .models import *
from django.core.urlresolvers import reverse
#全部信息
def departall(request):
bookinfo_list =depart.objects.all()
context={
'departName':bookinfo_list,
'titlt':'这是部门名'
}
return render(request=request,template_name='companyall/departall.html',context=context)
#显示一个信息
def departMobanOne(request,pk):
bookinfo_list =depart.objects.get(pk=pk)
context={
'departName':bookinfo_list,
'titlt':'这是部门名'
}
return render(request=request,template_name='companyall/depart_info.html',context=context)
def depart_add(request):
return render(request=request,template_name='companyall/depart_add.html',context=None)---渲染模板
#增加内容
def departNewAdd(request):
#处理新增
infos=request.POST ------要与htm里form表单的方法相一致
depart1=infos.get('btitle')
#包装对象
depart2=depart()
depart2.dname=depart1
#增加对象
depart2.save()
#return HttpResponse('ok') --------转发
#return HttpResponseRedirect()
return HttpResponseRedirect(reverse('com:departall'))-------------重定向
#增加成功之后的页面
def departAddO(request):
return HttpResponse('ok')
(四)--创建一个与与app同级的templase文件
里面尽量在创建一个与app同名的文件夹,在他下面在创建你所需的html文件(供views.py文件使用)
(depart_add.html)
删
def depart_delete(request):
pk=request.GET.get('pk')
ret=depart.objects.filter(pk=pk)
ret.delete()
return HttpResponseRedirect(reverse('com:departall'))
改
def depart_update(request):
pk=request.GET.get('pk')
depart1=depart.objects.get(pk=pk)
context={
'depart1':depart1
}
return render(request=request,template_name='companyall/depart_update.html',context=context)
def depart_update_handler(request):
#获取对象
infos=request.POST
#获取属性
pk=infos.get('pk')
dname=infos.get('btitle')
#包装对象
Depart=depart.objects.filter(pk=pk)[0]
Depart.dname=dname
#修改对象
Depart.save()
#重定向
return HttpResponseRedirect(reverse('com:departall'))
(depart_update.html)
(五)链接服务器,输入对应的url正则
网友评论