给django分页器点个赞

 项目的html表格分页一开始是由javascript写的,写完后足足有160行,各种判断处理,可以说是又长又臭,而且始终无法解决选择获取数据后所带来的表格跳页后的页面刷新处理(疑问一)

在将javascipt+ajax改为django的分页+submit后,问题迎刃而解

以下便是django的分页处理相关代码

django后端代码:

allprojects = '所有项目'
server = '0.0.0.0'

def get_data_by_project(model, username, project):
  if project == allprojects:
    data = model.objects.filter(Actor=username)
  else:
    data = model.objects.filter(Q(Project=project) & Q(Actor=username))
  return data if data else None

def get_data_or_create(model, username, server):
  data = model.objects.filter(Actor=username)
  # 如果data为空,就新增一条数据
  if not data:
    model.objects.get_or_create(yoursqlinfo, Server=server)
  data = model.objects.filter(Actor=username)
  return data

@login_required(login_url='/login/')
def myhtml(request):
  username = request.session.get('user')
  if request.GET:
    # 前端select对应项后,从数据库获取对应数据
    project = request.GET.get('chooseproject')
    data = get_data_by_project(testtable, username, project)
  else:
    # 第一次进入页面
    project = allprojects
    data = get_or_create_data(testtable, username, server)

  # django的分页器,每页10个数据
  paginator = Paginator(data, 10)
  page = request.GET.get('page')

  try:
    data = paginator.page(page)
  except PageNotAnInteger:
    data = paginator.page(1)
  except EmptyPage:
    data = paginator.page(paginator.num_pages)
  return render(request, 'myhtml.html', {'username': username,'data': data,'project': project})

 

html页面代码


<script type="text/javascript">
window.onload = function(){
  $('#chooseproject').val('{{ project }}');
}
script>



<form method="GET" id="chooseform">
  <select class="custom-select" id="chooseproject" name="chooseproject" style="width: 120px;float: left;padding: 0 15px;height: 30px">
  <option>所有项目option>
  <option>项目一option>
  <option>项目二option>
  select>
form>



<div style="float: right; margin-right: 150px;">
  {% if not data.has_previous%}
  <span><a>First a>span> |
  {% else %}
  <span><a href="?chooseproject={{ project }}&page=1">First a>span> |
  {% endif %}
  {% if data.has_previous %}
  <span><a href="?chooseproject={{ project }}&page={{ data.previous_page_number }}">Previous a>span> |
  {% else %}
  <span>Previous span> |
  {% endif %}
  {% if data.has_next %}
  <span id="nextpage"><a href="?chooseproject={{ project }}&page={{ data.next_page_number }}">Next a>span> |
  {% else %}
  <span><a>Next a>span> |
  {% endif %}
  {% if not data.has_next %}
  <span><a>Last a>span> |
  {% else %}
  <span><a href="?chooseproject={{ project }}&page={{ data.paginator.num_pages }}">Last a>span> |
  {% endif %}
   Page <span><a>{{ data.number }}a>span>/<span><a>{{ data.paginator.num_pages }}a>span>
div>


<script type="text/javascript">
  $('#chooseproject').change(function(){
    $('#chooseform').submit();
  });
script>

 

<a href="?chooseproject={{ project }}&page=xxx">

表示在点击后,其会发送对应的get请求

以上,便是django的分页器

 

你可能感兴趣的:(给django分页器点个赞)