实现目标及功能,增删改,并且实现搜索,分页,日期插件,删除提示,以及批量导入等功能
软件版本:
python3.5
django1.11
一 用pycharm创建一个项目,名字自定义
二 编辑urls.py
1 from django.conf.urls importurl, include2 from django.contrib importadmin3 from hnf importviews4
5 urlpatterns =[6 #无论访问那个页面都会跳转到登陆页面
7 url(r'^$', views.login),8 #登陆
9 url(r'^login', views.login),10 #注销
11 url(r'^logout', views.logout),12 #搜索
13 url(r'^search', views.search, name='search'),14 #django自带后台
15 url(r'^admin/', admin.site.urls),16 #展示页面
17 url(r'^asset/list/$', views.asset_list, name='asset_list'),18 url(r'^asset/add/$', views.asset_add),19 url(r'^asset/edit/(?P\d+)/$', views.asset_edit),20 url(r'^asset/del/(?P\d+)/$', views.asset_del),21 #导入
22 url(r'^asset/import/$', views.asset_import),23 #导入模板
24 url(r'^asset/tpl/$', views.asset_tpl),
三 创建数据库,我这里默认用的sqlite
1 from django.db importmodels2
3
4 #Create your models here.
5
6
7 classAsset(models.Model):8 """
9 资产表10 """
11 brand = models.CharField(verbose_name='品牌', max_length=32)12 model = models.CharField(verbose_name='型号', max_length=32)13 number = models.CharField(verbose_name='编号', max_length=32)14 leader_time = models.DateTimeField(verbose_name='领用时间', max_length=32)15 leader = models.CharField(verbose_name='领用人', max_length=32)16 return_time = models.DateTimeField(verbose_name='归还时间', max_length=32,null=True)17 other = models.CharField(verbose_name='备注', max_length=128,null=True)18
19 def __str__(self):20
21 returnself.leader22
23 classMeta:24 verbose_name="资产表"
25 verbose_name_plural = verbose_name
然后用下面两条命令去生成数据库
python3 manage.py makemigrations
python3 manage.py migrate
四 更改views.py
1 importos2 importmimetypes3 from django.shortcuts importrender, redirect4 from django.http importFileResponse5 from django.conf importsettings6 importxlrd7 from asset importmypage8 from hnf.forms.customer importUserinfoForm9 from hnf.forms.asset importAssetForm10 from hnf importmodels11
12 from django.contrib importauth13 from django.contrib.auth.decorators importlogin_required14 from hnf.utils.urls importmemory_reverse15
16 #Create your views here.
17 #登录页面
18 deflogin(request):19 if request.method == "GET":20 return render(request, "login.html")21 else:22 next_url = request.GET.get("next")23
24 username = request.POST.get("username")25 pwd = request.POST.get("password")26 user_obj = auth.authenticate(request, username=username, password=pwd)27 ifuser_obj:28 auth.login(request, user_obj) ## 给该次请求设置了session数据,并在响应中回写cookie
29 ifnext_url:30 returnredirect(next_url)31 else:32 return redirect("/asset/list/")33 else:34 return render(request, "login.html", {"error_msg": "用户名或密码错误"})35
36 #注销页面
37 deflogout(request):38 auth.logout(request)39 return redirect("/login/")40
41 defsearch(request):42 q = request.GET.get('q')43 error_msg = ''
44
45 if notq:46 error_msg = '请输入关键词'
47 return render(request, 'result.html', {'error_msg': error_msg})48
49 #post_list = models.Asset.objects.filter(leader__icontains=q)
50 #for i in post_list:
51 data_list=models.Asset.objects.filter(leader__contains=q)52 return render(request, 'result.html', {'error_msg': error_msg, 'post_list': data_list})53
54
55 @login_required()56 defasset_list(request):57 """
58 资产列表59 :return:60 """
61 data_list =models.Asset.objects.all()62 print(data_list)63 total_count =data_list.count()64
65 current_page = request.GET.get("page")66
67 page_boj = mypage.MyPage(current_page, total_count, url_prefix="asset/list")68 data = data_list[page_boj.start:page_boj.end] #从第几页显示到第几页
69
70 page_html = page_boj.page_html() #页面
71 page_num = page_boj.num() #序号
72
73 return render(request, 'asset_list.html', {'data_list': data, 'page_html': page_html, 'num': page_num})74
75
76 defasset_add(request):77 """
78 添加资产79 :param request:80 :return:81 """
82 if request.method == 'GET':83 form =AssetForm()84 return render(request, 'asset_add.html', {'form': form})85 form = AssetForm(data=request.POST)86 ifform.is_valid():87 form.save()88 return redirect('/asset/list/')89 return render(request, 'asset_add.html', {'form': form})90
91
92 defasset_edit(request, cid):93 """
94 编辑资产95 :return:96 """
97 obj = models.Asset.objects.get(id=cid)98 if request.method == 'GET':99 form = AssetForm(instance=obj)100 return render(request, 'asset_edit.html', {'form': form})101 form = AssetForm(data=request.POST, instance=obj)102 ifform.is_valid():103 form.save()104 return redirect('/asset/list/')105 return render(request, 'asset_edit.html', {'form': form})106
107
108 defasset_del(request, cid):109 """
110 删除资产111 :param request:112 :param cid:113 :return:114 """
115 #models.Asset.objects.filter(id=cid).delete()
116 #117 #return redirect('/asset/list/')
118
119 origin = memory_reverse(request, 'asset_list')120 print(origin)121 if request.method == 'GET':122 return render(request, 'delete.html', {'cancel': origin})123 models.Asset.objects.filter(id=cid).delete()124 returnredirect(origin)125
126
127 defasset_import(request):128 """
129 批量导入用户130 :param request:131 :return:132 """
133
134 if request.method == 'GET':135 return render(request, 'asset_import.html')136
137 context = {'status': True, 'msg': '导入成功'}138 try:139 customer_excel = request.FILES.get('customer_excel')140 """
141 打开上传的Excel文件,并读取内容142 注:打开本地文件时,可以使用:workbook = xlrd.open_workbook(filename='本地文件路径.xlsx')143 """
144 workbook = xlrd.open_workbook(file_contents=customer_excel.file.read())145
146 #sheet = workbook.sheet_by_name('工作表1')
147 sheet =workbook.sheet_by_index(0)148 row_map ={149 0: {'text': '品牌', 'name': 'brand'},150 1: {'text': '型号', 'name': 'model'},151 2: {'text': '编号', 'name': 'number'},152 3: {'text': '领用时间', 'name': 'leader_time'},153 4: {'text': '领用人', 'name': 'leader'},154 5: {'text': '归还时间', 'name': 'return_time'},155 6: {'text': '备注', 'name': 'other'},156
157 }158 object_list =[]159 for row_num in range(1, sheet.nrows):160 row =sheet.row(row_num)161 print(row)162 row_dict ={}163 for col_num, name_text inrow_map.items():164 row_dict[name_text['name']] =row[col_num].value165 object_list.append(models.Asset(**row_dict))166
167 models.Asset.objects.bulk_create(object_list, batch_size=20)168 exceptException as e:169 context['status'] =False170 context['msg'] = '导入失败'
171
172 return render(request, 'asset_import.html', context)173
174
175 defasset_tpl(request):176 """
177 下载批量导入Excel列表178 :param request:179 :return:180 """
181 tpl_path = os.path.join(settings.BASE_DIR, 'hnf', 'files', '批量导入资产模板.xlsx')182 content_type =mimetypes.guess_type(tpl_path)[0]183 print(content_type)184 response = FileResponse(open(tpl_path, mode='rb'), content_type=content_type)185 response['Content-Disposition'] = "attachment;filename=%s" % 'asset_excel_tpl.xlsx'
186 return response
View Code
五 在templates下面添加html页面,我这里举例是asset_list页面
1 {% extends 'layout.html' %}2
3 {% block content %}4
5
6
7
8 添加资产9
10
11 批量导入12
13
14
15 {# {% csrf_token %}#}16
17 搜索
18
19
20