Django-如何通过API服务器中的<a href=""> to a view

时间:2018-09-12 10:14:39

标签: python django

I have a category dropdown list in a template. I don't want to hard code it and write separate list views for each category. So is there a way to pass a value from <a href=""> to a view? I guess self.request.GET.get('category search') never works because there is no <form method="get"> tag. Therefor it always returns None due to the return queryset.none() statement.

home.html:

<div class="dropdown-menu" aria-labelledby="navbarDropdown">
    {% if all_categories %}
        {% for category in all_categories %}
            <a name="category search" href="{% url 'book:category_search' category.id %}"> {{ category }} </a>
        {% endfor %}
    {% endif %}
</div>

book.urls.py:

urlpatterns = [
    .........
    path('categories/<int:pk>', views.CategorySearchView.as_view(), name='category_search'),
]

book.views.py:

class CategorySearchView(generic.ListView):

    template_name = 'book/search.html'
    model = Book
    context_object_name = 'book_list'
    paginate_by = 100

    def get_queryset(self):
        queryset = super().get_queryset()
        search = self.request.GET.get('category search')
        if search:
            queryset = Book.objects.filter(categories__id=search)
            return queryset
        else:
            return queryset.none()

1 个答案:

答案 0 :(得分:2)

由于您的网址包含<int:pk>

path('categories/<int:pk>', views.CategorySearchView.as_view(), name='category_search'),

您可以在视图中访问self.kwargs['pk']

def get_queryset(self):
    queryset = super().get_queryset()
    search = self.kwargs.get('pk')
    if search:
        queryset = Book.objects.filter(categories__id=search)
        return queryset
    else:
        return queryset.none()

顺便说一句,如果查询字符串中有self.request.GET,则应使用pk,例如/categories/?pk=1。当您使用method=GET提交表单时,表单字段将包含在查询字符串中。但您也可以使用带有查询字符串的链接,例如<a href="/categories/?pk=1">my link</a>