【问题标题】:How to Sort a Django ListView on Button Click如何在按钮单击时对 Django ListView 进行排序
【发布时间】:2020-03-12 06:50:34
【问题描述】:

我正在制作一个包含大量活动帖子(派对、聚会、筹款活动等)的网站。

我希望用户能够按事件帖子的创建日期 (created_date) 和事件帖子在按钮单击时发生的日期 (start_date) 对帖子进行排序。

用户可以通过两种方式对 ListView 进行排序(根据我的 models.py 按 created_date 或 start_date) 所以我希望按钮是一个切换按钮,点击它once 将按 start_date 过滤,再次单击按钮(页面刷新后)将按 created_date 过滤。

我的 home.html 包含用于显示帖子的按钮和 for 循环:

<!-- THE EVENT FEED -->
<div class="feed">
  <h2>Event Feed</h2>
  <!--BUTTON TO FILTER EVENT FEED-->
  <div style = "border-top: solid 1px #eee; width:100%;align-items: center;display: flex;flex-direction: column;">

   <a href="{% url 'whsapp-home' %}?ordering={% if ordering == 'created_date' %}-start_date{% else %}-created_date{% endif %}"><button>Filter by Event Date</button></a>
   <!--<button data-text-swap="Filter by Event Date"></button>-->
  </div>

  <div class="chat">
    {% for post in posts %}
    <div class="your messages">
      <div class="message">
        <b>{{ post.title}}</b>
      </div>
    </div>
    {% endfor %}
    </div>
  </div>

这是我基于班级的帖子视图:

class PostListView(ListView):
    model = Post
    template_name = 'whsapp/home.html' # FOLLOW THIS NAMING SCHEME <app>/<model>_<viewtype>.html
    context_object_name = 'posts'
    def get_ordering(self):
        ordering = self.request.GET.get('ordering','created_date') #Order live feed events according to closest start date events at the top
        return ordering

有谁知道我该如何实现这个?

【问题讨论】:

  • 我在发布之前看到了这个问题。这个问题在这里并不适用,因为我不介意网站是否刷新,所以我不需要该页面上的动态 JS 或基于 JQuery 的解决方案。此外,他们正在使用 pk 过滤对象,而我正在尝试使用 ListView 的内置参数
  • 如果你不想使用 js,你可以使用两个视图和 url 同一个模板

标签: python django listview


【解决方案1】:

所以我又摆弄了一些 if 语句,通过设置 3 路条件,我能够创建可切换按钮

home.html:

<a href="{% if request.get_full_path == '/' %}?ordering=-start_date{% elif request.get_full_path == '/?ordering=-start_date' %}/?ordering=-created_date{% elif request.get_full_path == '/?ordering=-created_date' %}/?ordering=-start_date{% endif %}"><button>Event Date</button></a>

views.py

class PostListView(ListView):
model = Post
template_name = 'whsapp/home.html' # FOLLOW THIS NAMING SCHEME <app>/<model>_<viewtype>.html
context_object_name = 'posts'
ordering = ['-created_date']
def get_ordering(self):
  ordering = self.request.GET.get('ordering','-created_date') #Order live feed events according to closest start date events at the top
  return ordering

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-27
    • 2022-12-10
    • 2014-12-18
    • 1970-01-01
    • 2020-03-28
    相关资源
    最近更新 更多