当用户选择下拉列表的值时,我需要更新模板。有可能通过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 %}
答案 0 :(得分: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
})