登录网站后,我想使用dataTable将数据呈现到index.html中的列中。 dataTable不显示任何数据。我知道我的问题在views.py中,因为我想将json对象返回给index.html。当我使用HttpReponse返回json对象时,它按以下格式正确返回了json对象,但在index.html中却没有。我的方法是我想将json对象返回给index.html并在dataTable列中呈现数据。任何帮助将不胜感激!
views.py
@login_required
def index(request):
if request.user.is_authenticated():
#if (Employee.objects.filter(emp_type__contains = "user").filter(user__username__contains = request.user.username)):
if (Employee.objects.filter(Q(emp_type__icontains = "user") | Q(emp_primary__icontains = 2)).filter(user__username__icontains = request.user.username)):
projects = Project.objects.filter(user__id__icontains = request.user.id)
'''paginator = Paginator(projects, 16)
page = request.GET.get("page")
try:
projects = paginator.page(page)
except PageNotAnInteger:
projects = paginator.page(1)
except EmtyPage:
projects = paginator.page(paginator.num_pages)
'''
data = serializers.serialize("json", projects)
output = [d['fields'] for d in json.loads(data)]
#return render(request, 'polls/index.html', {"data": data})
#return render(request, 'polls/index.html', {'projects': projects})
return HttpResponse(data, content_type="application/json")
elif (Employee.objects.filter(emp_type__contains = "admin").filter(user__username__contains = request.user.username)):
projects = Project.objects.all()
'''paginator = Paginator(projects, 16)
page = request.GET.get("page")
try:
projects = paginator.page(page)
except PageNotAnInteger:
projects = paginator.page(paginator.num_pages)
'''
data = serializers.serialize("json", projects)
output = [d['fields'] for d in json.loads(data)]
#return render(request, 'polls/index.html', {'projects': projects})
#return render(request, 'polls/index.html', {"data": data})
return HttpResponse(data, content_type="application/json")
else:
return render(request, 'polls/index.html', {})
==== index.html
{% extends 'base.html' %}
<head>
<meta charset = "utf-8">
<meta name = "viewport" content = "width = device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
{% load static %}
<!-- <link rel="stylesheet" href = "{% static 'polls/style.css'%}" type = "text/css"> -->
</head>
{% block body %}
<div class = "container">
<form action="/ajax/validate_username/" id="post-form" method="POST" style="width=1150px">
{% csrf_token %}
<div class = "pagination">
<input type = "text" id = "talk"></input>
<form>
<table class = "table table-hover table-dark" id="project_table">
<thead>
<tr>
<th>Project No</th>
<th>Project Section</th>
<th>Project Description</th>
<th>Project ID</th>
<th>Employee Name</th>
<th>Funding Year</th>
</tr>
<!-- <tr>
<th scope="col" ><input type = "text" name = "search_no" id="no_id" placeholder = "Search"><input type="submit"></input></input></th>
<th scope="col" ><input type = "text" name = "search_section" id="section_id" placeholder = "Search"><input type="submit"></input></input></th>
<th scope="col" ><input type = "text" name = "search" id = "search1" placeholder = "Search"><input type="submit"></input></input></th>
<th scope="col" ><input type = "text" name = "search_id" id="project_id" placeholder = "Search"><input type="submit"></input></input></th>
<th scope="col" ><input type = "text" name = "search_name" id="employee_id" placeholder = "Search"><input type="submit"></input></input></th>
<th scope="col" ><input type = "text" name = "search_year" id="funding_id" placeholder = "Search"><input type="submit"></input></input></th>
</tr> -->
</thead>
<tfoot>
<tr>
<th>Project No</th>
<th>Project Section</th>
<th>Project Description</th>
<th>Project ID</th>
<th>Employee Name</th>
<th>Funding Year</th>
</tr>
</tfoot>
<tbody>
<!-- { if projects %}
{ for project in projects%}
<tr>
<td>{project.pro_no}} </td>
<td scope = "row"><a href = "{ url 'emp_detail' project.id %}">{project.pro_section}}</a></td>
<td>{project.pro_description}}</td>
<td>{project.pro_ID}}</td>
<td>{project.pro_description}}</td>
<td>{project.pro_ID}}</td>
<td>
{ for emp in project.employee.all %}
<table>
<tr><td>{emp.first_name}}</td></tr>
</table>
{ endfor %}
</td>
<td>
{ for emp in project.employee.all %}
<table>
<tr><td>{emp.funding_year}}</td></tr>
</table>
{ endfor %}
</td>
</tr>
{ endfor %}
{ endif %}
<span class = "step-links">
{ if projects.has_previous %}
<i class = "fa fa-angle-double-left" style="color:black"></i>
<a href = "?page={projects.previous_page_number}}">Previous</a>
{ endif %}
<span class = "current">
Page {projects.number}} of {projects.paginator.num_pages}}.
</span>
{ if projects.has_next %}
<i class="fa fa-angle-double-right" style="color:black"></i>
<a class="fa fa-angle-double-right" style="color:black" href = "?page={projects.next_page_number}}">Next</a>
{ endif %}
<span> -->
</tbody>
</table>
</form>
</div>
</div>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script type="text/javascript" src=" https://cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src=" https://cdn.datatables.net/buttons/1.2.4/js/dataTables.buttons.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jszip/2.5.0/jszip.min.js"></script>
<script type="text/javascript" src="https://cdn.rawgit.com/bpampuch/pdfmake/0.1.24/build/pdfmake.min.js" ></script>
<script type="text/javascript" src="https://cdn.rawgit.com/bpampuch/pdfmake/0.1.24/build/vfs_fonts.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/1.2.4/js/buttons.html5.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/1.2.1/js/buttons.print.min.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.13/css/jquery.dataTables.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/buttons/1.2.4/css/buttons.dataTables.min.css">
<!-- <script src="/static/scripts/main.js"></script> -->
<script type="text/javascript">
$(document).ready(function() {
console.log("search function is working!");
$("#project_table").dataTable({
"processing": false,
"ajax": {
"processing": false,
"url": "{% url 'index' %}",
"dataSrc": ""
},
"columns": [
{"data": "fields.pro_description"},
{"data": "pk"}
]
});
});
</script>
{% endblock %}
== urls.py
from django.conf.urls import url
from django.contrib.auth.views import(
login, logout, password_reset, password_reset_done, password_reset_confirm,
password_reset_complete
)
from django.contrib.auth.views import(
PasswordResetView,
PasswordResetDoneView,
PasswordResetConfirmView,
PasswordResetCompleteView
)
from django.urls import reverse_lazy
from django.contrib.auth import views as auth_views
from .import views
from .import forms
#app_name = 'polls'
urlpatterns = [
#url(r'^$', views.index_.as_view(), name = 'index'),
url(r'^$', views.index, name = 'index'),
url(r'^(?P<project_id>[0-9]+)/emp_detail/$', views.emp_detail, name = 'emp_detail'),
url(r'^search/$', views.search, name = 'search'),
url(r'^project_working/$', views.project_working_detail, name = 'project_working_detail'),
url(r'^login/$', login, {'template_name': 'polls/login.html'}, name = 'login'),
url(r'^logout/$', logout, {'template_name':'polls/logout.html'}, name = 'logout'),
url(r'^register/$', views.register, name = 'register'),
url(r'^signup/$', views.SignUpView.as_view(), name='signup'),
url(r'^ajax/validate_username/$', views.validate_username, name = 'validate_username'),
#url(r'^ajax/object/$', views.Object.as_view(), name = 'object'),
url(r'^reset-password/$', password_reset, name = 'reset_password'),
url(r'^reset-password/done/$', password_reset_done, name = 'password_reset_done'),
url(r'^reset-password/confirm/(?P<uidb64>[0-9A-Za-z]+)-(?P<token>.+)/$', password_reset_confirm, name = 'password_reset_confirm'),
url(r'^reset-password/complete/$', password_reset_complete, name = 'password_reset_complete'),
url(r'^renew/$', views.renew_book_librarian, name = 'renew_book_librarian'),
]
== json对象
[{"model": "polls.project", "pk": 2, "fields": {"user": 1, "pro_no": "9.1", "pro_section": "9.1 ABC", "pro_description": "SUPPORT ABCDE", "pro_ID": "001332-H", "percent": 0.04, "employee": [1]}}, {"model": "polls.project", "pk": 5, "fields": {"user": 1, "pro_no": "9.1", "pro_section": "9.1 ABC", "pro_description": "SUPPORT ABCDE FY-20", "pro_ID": "2014", "percent": 0.02, "employee": [1]}}]
答案 0 :(得分:0)
您应该真正将某些逻辑与索引视图分开。如果您发现您正在对数据表的JSON数据执行AJAX请求。因此,您应该创建一个不同的URL来处理为AJAX请求返回该数据。这将清理您的索引视图,并将数据与要求数据的页面分开。
例如,“ / index”将返回原义的index.html页面,然后该页面可以查询“ / index / projects”或更通用的“ / projects”,这将返回所需的所有不同项目的JSON对象。通过这种方法,您还可以让更多页面获取此数据,而不必在视图逻辑中重复进行操作,这使您的代码保持干燥且易于阅读。
侧面说明:在python中,使用#而不是三引号将代码注释掉,通常使用#注释掉代码,而使用三引号则更多地用于多行字符串和文档创建。
此外,在以后的问题中,请尝试仅发布与错误直接相关的代码,从而使人们不必花太多时间来阅读。