将json对象返回到索引.html并将数据呈现到dataTable列

2024-03-28 17:05:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我想使用dataTable将数据呈现到索引.html在我登录我的网站之后。dataTable不显示任何数据。我知道我的问题是视图.py,因为我想将json对象返回到索引.html. 当我使用HttpReponse返回json对象时,它正确地返回了如下格式的json对象,而不是索引.html. 我的方法是将json对象返回给索引.html并在dataTable列中呈现数据。任何帮助都将不胜感激!!你知道吗

在视图.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', {})

你知道吗==== 索引.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 %}

你知道吗== 网址.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]}}]

Tags: textnameprojectidurlinputtypepage
1条回答
网友
1楼 · 发布于 2024-03-28 17:05:07

你真的应该把一些逻辑从索引视图中分离出来。如果您注意到正在对datatable的JSON数据执行AJAX请求。因此,您应该创建一个不同的URL来处理AJAX请求返回的数据。这将清理索引视图,并将数据从请求数据的页面中分离出来。你知道吗

例如“/index”将返回文本索引.html页,然后该页可以查询“/index/projects”或更一般的“/projects”,它为您想要的所有不同的项目返回JSON对象。使用这种方法,您还可以让更多的页面获取这些数据,而不必在视图逻辑中重复自己的操作,这样可以保持代码的干性和易读性。你知道吗

旁注:在python注释代码中,使用#而不是三重引号,使用#注释代码是标准的,而三重引号更适用于多行字符串和文档创建。你知道吗

另外,在以后的问题中,尽量只发布与错误直接相关的代码,这样回答问题的人就不必读那么多。你知道吗

相关问题 更多 >