【问题标题】:Django filter feature with ajax not working带有ajax的Django过滤器功能不起作用
【发布时间】:2021-08-16 09:31:48
【问题描述】:

我有一个用于跟踪工作申请的表格,并且我正在尝试实现过滤功能。我想用分页显示结果。但是,我在尝试这样做时遇到了错误,并且似乎无法摆脱它。我希望在不刷新页面的情况下显示结果。我认为问题出在查询上。

请帮忙.... :(((

这是我的代码:

模板文件

 <ul id="filter_list" class="dropdown-menu">
     <li><a href="#">Alphabetical Order (A-Z)</a></li>
     <li><a href="#">Application Date (Ascending)</a></li>
     <li><a href="#">Application Date (Descending)</a></li>
     <li><a href="#">Closing Date</a></li>
 </ul>

 <div id="table_results">

 <div>

 <script>

    $(".dropdown-menu a").click(function(){
    var selected_filter = $(this).text();


    $.ajax({
        url:'{% url "stu_filter_applications" %}',
        data:{
            "filter_category": selected_filter,
        },
        dataType:'json',
        success: function (response) {
            //I want the page to not refresh here                  
            },
          error: function (response) {
            console.log(response.errors);
          },
        });

    });
</script>

views.py:

def stu_filter_applications(request):
    filter_cat = request.GET.get("filter_category", None)
    student = StudentUser.objects.get(user=request.user)

    if filter_cat == "Alphabetical Order (A-Z)":       
        int_applications = 
        InternshipApplication.objects.filter(student=student).
        order_by('internship__internship_title')

    if filter_cat == "Application Date (Ascending)":
        int_applications = 
        InternshipApplication.objects.filter(student=student).
        order_by('application_date')

    if filter_cat == "Application Date (Descending)":
        int_applications = 
        InternshipApplication.objects.filter(student=student).
        order_by('-application_date')

    if filter_cat == "Closing Date":
         int_applications = 
         InternshipApplication.objects.filter(student=student).
         order_by('-internship__internship_deadline')

     applications = []

    for app in int_applications:
        internship = Internship.objects.get(id=app.internship.id)
        recruiter = Recruiter.objects.get(id=internship.recruiter.id)
        applications.append((internship,recruiter,app))


    for internship, recruiter, app in applications:
        print(internship)
        print(recruiter)
        print(app)

    paginator = Paginator(applications, 3)
    page = request.GET.get('page', 1)

        try:
            applications = paginator.page(page)

        except PageNotAnInteger:
            applications = paginator.page(1)

        except EmptyPage:
            applications = paginator.page(paginator.num_pages)
        context = {    
              'applications': applications,
              'filter_by': filter_cat,
         }
            return render(request,'track_internship.html', context)
    

track_internship.html

<ul id="filter_list" class="dropdown-menu">
      <li><a href="#">Alphabetical Order (A-Z)</a></li>
      <li><a href="#">Application Date (Ascending)</a></li>
      <li><a href="#">Application Date (Descending)</a></li>
      <li><a href="#">Closing Date</a></li>
</ul>
     

        
  <table style="width:100%; margin-top: 20px;"  id="app_table" class="table">
                <thead>
                    <tr style="background-color:#012D6C; color:white;" 
            class="table_row">
                        <th>Company</th>
                        <th>Title</th>
                        <th>Type</th>
                        <th>Link to advert</th>
                        <th>Posted Date</th>
                        <th>Closing Date</th>
                        <th>Application Date</th>
                        <th>Status</th>
                    </tr>
                </thead>

        <div id="table_results">
                <tbody>
                    {% for internship, recruiter, app in applications %}
                    <tr style="background-color: #E9F4FF" class="table_row">
                        <td>{{ recruiter.company_name }}</td>
                        <td>{{ internship.internship_title }}</td>
                        <td>{{ internship.internship_mode}}</td>
                        <td><a style="color:blue; text-decoration: 
                underline;" href="http://127.0.0.1:8000/view_details/{{ 
                internship.id }}">Click here</a></td>
                        <td>{{ internship.posted_date }}</td>
                        <td>{{ internship.internship_deadline }}</td>
                        <td>{{ app.application_date }}</td>
                        <td>{{ app.status }}</td>
                    </tr>
                    {% endfor%}
                </tbody>
            </table>
        

        {% if applications.has_other_pages %}
        
        <div class="pagination">
            {% if applications.has_previous %}
            <a href="?page={{ applications.previous_page_number }}"><i 
            class="fa fa-chevron-left" aria-hidden="true"></i></a>
            {% else %}
                <a class="disabled"><span><i class="fa fa-chevron-left" aria- 
             hidden="true"></i></span></a>
            {% endif %}
            
            {% if applications.number|add:'-2' > 1 %}
                <a href="?page={{ applications.number|add:'-3' }}">&hellip; 
            </a>
            {% endif %}
            
            {% for i in applications.paginator.page_range %}
                {% if applications.number == i %}
                    <a class="active"><span>{{ i }} <span class="sr-only"> 
                (current)</span></span></a>
                {% elif i > applications.number|add:'-3' and i < 
            applications.number|add:'3' %}
                    <a href="?page={{ i }}">{{ i }}</a>
                {% endif %}
            {% endfor %}
            
            {% if applications.paginator.num_pages > 
             applications.number|add:'4' %}
                <a href="?page={{ applications.number|add:'3' }}">&hellip; 
            </a>
            {% endif %}
            
            {% if applications.has_next %}
                <a href="?page={{ applications.next_page_number }}"><i 
            class="fa fa-chevron-right" aria-hidden="true"></i></a>
            {% else %}
                <a class="disabled"><span><i class="fa fa-chevron-right" 
            aria-hidden="true"></i></span></a>
            {% endif %}

    

models.py

class StudentUser(models.Model):

   user = models.OneToOneField(User, on_delete=models.CASCADE)
   gender = models.CharField(max_length=1, choices=GENDER_CHOICES, 
   null=True, blank=True)

 class Internship(models.Model):

     recruiter = models.ForeignKey(Recruiter, on_delete=models.SET_NULL, null=True)
     internship_title = models.CharField(max_length=100)
     internship_deadline = models.DateField()
 

 class InternshipApplication(models.Model):
     internship = models.ForeignKey(Internship, on_delete=models.CASCADE)
     student = models.ForeignKey(StudentUser,on_delete=models.SET_NULL, null=True)
     application_date = models.DateField()

【问题讨论】:

  • 您面临的确切错误是什么?目前尚不清楚您要做什么,因此如果您过滤结果,您希望 ajax 调用填充新数据,然后在页面之间移动过滤结果,请使其更清晰。
  • @AAB,我有一个表格,它以分页的形式显示结果。单击过滤器后,例如按截止日期排序,我希望页面更新,但这次是按截止日期对作业进行排序。我希望我是清楚的。
  • 你能把错误贴出来,这样更容易调试
  • @AAB,我没有收到错误,但它不起作用。以前,它告诉我该对象不存在属性实习.internship_title。关闭日期相同。但现在,不是说 ://
  • 如果您删除 request.is_ajax(),并打开带有页面参数的 url 并过滤它什么都不打印?您正在返回 html,所以应该打印的东西不能为空白您可以发布您正在呈现的 html 吗?

标签: django ajax django-models django-views django-templates


【解决方案1】:

根据您的模型、模板、视图,您需要更改以下内容:

  1. 将实习生.internship_deadline 更改为实习__internship_deadline 并将实习生.internship_title 更改为实习__internship_title。

  2. 您可以将实习、招聘人员、int_applications 作为单独的对象传递。 int_applications 应该返回多个对象,这与您使用 .get() 的招聘人员和实习生不同

  3. 在使用 orderby 的分页模板中,url 必须如下:

    ?page=value&filter_category=value

  4. 在您的 views.py 中,您似乎只是根据用户输入对值进行排序,因此我建议您将其更改为 order_by,因为您除了排序之外没有过滤任何内容。

【讨论】:

  • 我更新了views.py的代码。请您提供进一步的帮助吗?
  • 第 3 部分和第 4 部分
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-07-08
  • 2021-10-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-15
  • 2020-11-24
相关资源
最近更新 更多