Remember some common code snippets in Django development

The first snow in 2018, later than in 2002

I remember sharing a series of articles related to Django development (search on the top right of the blog), including templates, views, routing, and more. Then this article adds some function code blocks commonly used in Django development process, including front-end and back-end related function codes. These code blocks are commonly used in normal development, so make a backup here for easy query.

Frontend function

Panel folding



This feature is often used in the side menu bar, panel folding can effectively keep the interface clean.

1
2
3
4
5
6
7
8
9
10
11
<div class="panel panel-success">
<div class="panel-heading" data-toggle="collapse" data-parent="#accordion" href="#collapse">
<h1 class="panel-title"><span class="glyphicon glyphicon-tag" aria-hidden="true"></span>Index</h1>
</div>
<div id="collapse" class="panel-collapse collapse out"> # out or in Control folding status
<div class="panel-body">
<a href="">index1</a><br><br>
<a href="">index2</a><br><br>
</div>
</div>
</div>

Form paging


The front-end of the table pagination is relatively simple. To achieve true pagination display data, you need to combine the back-end code, which will be introduced later in the article.

1
2
3
4
5
6
7
8
9
10
11
12
13
<!-- Pagination -->
<form action="{% url 'asset_list' %}" method="POST">
{% csrf_token %}
<ul class="pagination pagination">
{% for i in page_list %}
<li><a href="{% url 'asset_list' %}?page={{ i }}&search_key={{search_key}}" class="active">{{ i }}</a></li>
{% endfor %}
&nbsp;
<li>
&nbsp;
</ li>
</ Ul>
</form>

Control table cell content wrap

Sometimes the content of the cells in the table is too long, which will make the whole table look bad. Therefore, you need to add the following style to the table columns with long content.

1
<td style="word-wrap:break-word;word-break:break-all;">test</td>


Sometimes you need to modify some form data. The previous method is to click a button to jump to a modified page, but this is not elegant enough, so you can choose to pop up an editable dialog box by clicking the button.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<form action="/index/" method="POST">
<div class="modal fade" id="update" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">
&times;
</button>
<h4 class="modal-title" id="myModalLabel">
Reminder box
</h4>
</div>
<div class="modal-body">
<label>KEY</label>
<input type="text" class="form-control" name="new_key" value="{{i.key_}}">
<label>VALUES</label>
<input type="text" class="form-control" name="new_value" value="{{i.value_}}">
</div>
<div class="modal-footer">
</button>
<button type="submit" name="update_id" value="{{i.id}}" class="btn btn-primary">
Confirm modification
</button>
</div>
</div>
</div>
</div>
</form>


This function is mainly used to remove data and remind you when modifying data.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<form action="/index/" method="POST">
<div class="modal fade" id="del" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">
&times;
</button>
<h4 class="modal-title" id="myModalLabel">
Reminder box
</h4>
</div>
<div class="modal-body">
Are you sure you want to delete the record?
</div>
<div class="modal-footer">
</button>
<button type="submit" name="del_id" value="{{i.id}}" class="btn btn-primary">
confirm delete
</button>
</div>
</div>
</div>
</div>
</form>

Search box auto completion


This is awesome. When searching for some resources, is it convenient to autocomplete?

1
2
3
4
5
6
7
8
9
<label for="autocomplete">Select Scan Plugin (required)</label><br>
<input class="form-control" id="autocomplete" name="vul_name" placeholder="Enter the vulnerability name"><br><br>
<script type="text/javascript">
$( "#autocomplete" ).autocomplete({
source: tags
});
</script>

ajax request

Sending a request with ajax is good or bad. For specific usage, please refer to: https://thief.one/2017/09/14/3/

Interface panel layout


This is purely for the sake of force.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<div class="container">
<div class="row">
<div class="col-md-3">
<div class="list-group">
<form class="list-group-item">
<a href="">test</a>
</form>
</div>
</div>
<div class="col-md-3">
<div class="list-group">
<form class="list-group-item">
<a href="">test2</a>
</form>
</div>
</div>
</div>
</div>

Forms radio button

The table display data is a common function. In general, multiple tabular data is required for deletion, so batch selection is very important. Batch selection in the general table can be achieved using a radio button.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
<!-- Import js -->
<script src="https://cdn.bootcss.com/jquery/2.1.1/jquery.min.js"></script>
<!-- Form Data -->
<div id="list">
<table class="table table-hover table-bordered table-striped">
<thead>
<tr>
<th><input type="checkbox" id="all" name="task_check_" value=""></th>
<th>ID</th>
<th>User</th>
</tr>
</thead>
<tbody>
<tr>
<th><input type="checkbox" id="" name="task_check" value=""></th>
<td> 01 </ td>
<td>nmask</td>
<td>
</td>
</tr>
</tbody>
</table>
</div>
<!-- js -->
<script>
$(document).ready(function () {
//Select all or none
$("#all").click(function () {
if (this.checked) {
$("#list :checkbox").prop("checked", true);
} else {
$("#list :checkbox").attr("checked", false);
}
});
/ / Set the check box
$("#list :checkbox").click(function () {
allchk ();
});
function selectAll(check){
$(check).click(function(){
if ($(check).is(':checked')) {
$(".list input").prop("checked",true);
}else{
$(".list input").prop("checked",false);
};
});
}
/ / Execute once when displayed
selectAll();
});
</script>

Backend function

Form paging

The front page of the front page is introduced, so how does the back end write paging function? The django framework has a built-in paging module Paginator, and other frameworks, such as flask.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
from django.core.paginator import Paginator
def page_fenye(objects,page,num=10):
'''Page function
@num: How many pieces of data are displayed per page
@page: current page number
@fenye_num: Number of digits displayed in the tab bar
@object_list: the data object displayed on this page
@page_range: The range of numbers displayed in the tab bar
@last_page: the number on the last page
'''
Pagination_num=6
fenye_num_av = fenye_num / 2
try:
page=int(page)
except:
page=1
if page<1:
page=1
range_first_page = page-fenye_num_av
range_last_page = page + fenye_num_av
if range_first_page<0:
range_first_page=0
Range_last_afraid = page _num
p = Paginator(objects, num)
page_range=list(p.page_range)[range_first_page:range_last_page]
last_page=len(p.page_range)
if page>last_page:
page=1
page1 = p.page(page)
object_list=page1.object_list
return object_list,page_range,last_page

However, after using it, the performance is not good, because every time you request a page, you need to get all the data first, and then use this module to calculate the data that this page needs to display. When all the data volume is relatively large, the return is slower (also Maybe I didn’t use this module). So I wrote a paging module myself.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
def fenye(all_num,page,num,page_list_num):
'''Page calculation
@all_num: Total database records
@page: current page number
@num: Number of records displayed per page
@page_list_num: How many numbers are displayed in the page navigation, to be even
@page_list_aver:page_list_num divided by 2
@page:Show the first few pages
@last_page: the number on the last page
@page_list: The range of numbers displayed in the tab bar
'''
page=int(page)
if all_num!=0:
Last_page = all_num/num-1 if all_num%num == 0 else all_num/num #calculate the last page of numbers
else:
last_page=0
page_list_aver=page_list_num/2
Page=last_page if page > last_page else page #Judge if the requested number of pages exceeds the range
if page > page_list_aver:
if last_page > page+page_list_aver:
page_list=range(page - page_list_aver , page + page_list_aver)
else:
page_list=range(last_page - (page_list_num-1), last_page + 1)
else:
if last_page > page_list_num:
page_list = range(page_list_num)
else:
page_list = range(last_page + 1)
return page,last_page,page_list

This does not need to query all the data in memory beforehand, but only need to query how many pieces of data exist in total (note that the query here is changed from select * to select count(*)). After getting the page returned by the paging function, you can combine the limit function in the sql statement to query the data content to be displayed on the paging page.

1
Select * from test limit page *num, num # page is the page number returned by the page, num is the number of data displayed on one page

session to do identity authentication

This function is used to verify the identity of the user. It can be used with the login function to write a decorator function to check whether there is a session value in the global. (The session value is a dictionary format that is generated when the user logs in.)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
def session_check(level=2,return_=False):
'''session_check decorator function for function
@level: can give users permission to distinguish
@return_: Jump to a different page after detecting that there is no session
'''
def dec(func):
def warp(request,*args,**kwargs):
if request.session.get('user_id',False) and int(request.session.get('level'))<=level:
return func(request,*args,**kwargs)
elif return_:
return HttpResponse('<head><meta http-equiv="refresh" content="0.0001;url=/login/"></head>')
else:
return HttpResponse('<head><meta http-equiv="refresh" content="0.0001;url=/error/"></head>')
return warp
return dec

If you use it, add it directly on the function that requires permission control:

1
2
3
4
@session_check(return_=True)
def vul_index(request):
''' Vulnerability Scan '''
pass

`For the time being, I thought about it. Let’s remember so much. After that, I will add some more, o.

本文标题:Remember some common code snippets in Django development

文章作者:nmask

发布时间:2018年01月26日 - 18:01

最后更新:2019年08月16日 - 15:08

原始链接:https://thief.one/2018/01/26/1/en/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

nmask wechat
欢迎您扫一扫上面的微信公众号,订阅我的博客!
坚持原创技术分享,您的支持将鼓励我继续创作!

热门文章推荐: