【问题标题】:Django dropdown filter with ajax?带有ajax的Django下拉过滤器?
【发布时间】:2018-09-23 13:24:32
【问题描述】:

当用户选择下拉列表的值时,我需要更新我的模板。是否有可能通过 ajax 调用或类似方法来做到这一点?如果用户选择下拉列表的值,该值将被发送到我的视图,并且我的页面中的内容将在不刷新页面的情况下更新,这将是完美的。

我尝试了不同的方法,但没有任何效果...欢迎任何建议。

这是我的缩短代码:

models.py

class Author(models.Model):
      id = models.IntegerField(primary_key=True)
      author = models.CharField(max_length=50)
      status = models.CharField(max_length=50)          

      [...]

views.py

def authors(request):
     authors = Author.objects.all()
     if request.method="GET":
         authors = Author.objects.filter(status = filter)

模板

<div class="dropdown">
  <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
    Choose status
  </button>
  <div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
    <a class="dropdown-item" href="#">Staff</a>
    <a class="dropdown-item" href="#">Admin</a>
          [...]
  </div>
</div>

{% for author in authors %}
{{author.author}}
{% endfor %}

【问题讨论】:

  • 你能分享你的models.py吗?

标签: python ajax django


【解决方案1】:

模板

<a class="dropdown-item" href="{% url 'admin' %}">Staff</a>
<a class="dropdown-item" href="{% url 'staff' %}">Admin</a>

urls.py

url(r'^admin/', authors_admin, name='admin'),
url(r'^staff/', authors_staff, name='staff'),

views.py

def authors_admin(request):
     authors = Author.objects.all()
     if request.method="GET":
         authors = Author.objects.filter(status = 'admin')
         return render(request, 'template.html', {
                  'authors ': authors 
         })

def authors_staff(request):
     authors = Author.objects.all()
     if request.method="GET":
         authors = Author.objects.filter(status = 'staff')
         return render(request, 'template.html', {
                  'authors ': authors 
         })

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-12
    • 1970-01-01
    • 2021-08-16
    • 1970-01-01
    • 2015-10-18
    • 1970-01-01
    相关资源
    最近更新 更多