【问题标题】:Ajax pagination with class based view具有基于类的视图的 Ajax 分页
【发布时间】:2020-12-18 00:21:54
【问题描述】:

我正在尝试在我的应用程序上应用带有分页的 ajax。使用基于类的 Listview

#views.py
class HomePage(ListView):
model = Video
template_name = 'index.html'


def get_context_data(self, **kwargs):
    context = super(HomePage, self).get_context_data(**kwargs)
    videos = Video.objects.filter(category='sub')
    paginator = Paginator(videos, 5)
    page = self.request.GET.get('page2')
    try:
        videos = paginator.page(page)
    except PageNotAnInteger:
        videos = paginator.page(1)
    except EmptyPage:
        videos = paginator.page(paginator.num_pages)

    context['videos'] = videos

    if self.request.is_ajax():
        html = render_to_string('videos/index.html', context, request=self.request)
        print(html)
    return JsonResponse({'form' : html })

主页模板脚本

<script type="text/javascript">
                        $(document).ready(function(event){
                            $(document).on('click', '.page-link', function(event){
                                event.preventDefault();
                                var page = $(this).attr('href');
                                console.log(page)
                                $.ajax({
                                    type: 'GET',
                                    url: ,
                                    data: {'page':'{{ page.number }}'},
                                    dataType: 'json',
                                    success: function(response){
                                        $('#ajax_page_template').html(response['form'])
                                        console.log("success")
                                       
                                    },
                                    error: function(rs, e){
                                        console.log(rs.responseText);
                                    },
                                });
                            });
                        });

                    </script>


1.当前错误在views.py中local variable 'html' referenced before assignment

2.我应该在 ajax --url 中输入什么:我尝试输入 url:page 但返回 url 到 127.0.0.1:8000/?page=2/?page=2.

【问题讨论】:

    标签: python-3.x django ajax django-rest-framework django-views


    【解决方案1】:

    我也遇到了同样的问题,然后解决了:

    在views.py中添加“paginate_by = 4”和def get_template_names:

    class HomePage(ListView):
        ...
        paginate_by = 4
    
    def get_template_names(self):
        template_name = 'list.html'
        if self.request.is_ajax():
            template_name = 'list_ajax.html'
        return template_name
    

    使用 2 个模板:

    带有 for 循环的新 list_ajax.html:

    {% for video in video_list %}
    ...
    {% endfor %}
    

    现有模板list.html:

    <div id="image-list">
      {% include 'list_ajax.html' %}
    </div>
    

    在脚本中:

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/js-cookie@2.2.1/src/js.cookie.min.js"></script>
    <script>
      var csrftoken = Cookies.get('csrftoken');
      function csrfSafeMethod(method) {
        // these HTTP methods do not require CSRF protection
        return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
      }
      $.ajaxSetup({
        beforeSend: function(xhr, settings) {
          if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
          }
        }
      });
    
      $(document).ready(function(){
        var page = 1;
        var empty_page = false;
        var block_request = false;
        var num_pages=parseInt('{{ page_obj.paginator.num_pages }}')
        $(window).scroll(function() {
            var margin = $(document).height() - $(window).height() - 200;
            if  ($(window).scrollTop() > margin && empty_page == false &&
            block_request == false) {
            block_request = true;
            page += 1;
            if(num_pages-page >= 0) {
            $.get('?page=' + page, function(data) {
                block_request = false;
                console.log(data)
                $('#image-list').append(data);
                }
            );
            }}
        });
      });
    </script>
    

    【讨论】:

      【解决方案2】:

      您必须在使用之前声明html 变量。像这样:

       html = ""
       if self.request.is_ajax():
           html = render_to_string('videos/index.html', context, request=self.request)
      

      您应该在ajax调用中放入的url是与相关视图(HomePage)相对应的那个。

      并更改以下行:

      return JsonResponse({'form' : html })
      

      收件人:

      render(request,'videos/index.html',JsonResponse(html))
      

      【讨论】:

      • 它显示 TypeError at / context must be a dict 而不是 JsonResponse
      • TypeError at / 为了允许序列化非字典对象,请将安全参数设置为 False。
      • 我不明白为什么我们必须更改视图-- html = " " 。在我的其他具有基于函数视图的应用程序中,一切正常,是否因为基于类的视图而发生?
      猜你喜欢
      • 2021-09-10
      • 2017-05-08
      • 2014-10-12
      • 2018-11-25
      • 1970-01-01
      • 2019-09-24
      • 1970-01-01
      • 2020-03-02
      • 1970-01-01
      相关资源
      最近更新 更多