【问题标题】:Passing arguments to Django CBV for queryset将参数传递给 Django CBV 以获取查询集
【发布时间】:2021-05-06 12:19:59
【问题描述】:

我试图弄清楚如何将参数从用户提交表单的通用视图传递到 cbv 模板视图。

我的第一个通用观点是这样的:

def homepage(request):

    if request.method == 'POST':
        form = SearchForm(request.POST)

        if form.is_valid():
            form_data = form.cleaned_data
            return redirect('filtered', city=form_data['city'], category=form_data['category'])

    else:
        form = SearchForm()
   return render(request, 'index.html', context={'form': form})

我想要实现的是,当用户选择一个城市和一个类别时,他会被提交到一个 TemplateView 主页,其中有一个基于所选城市和所选类别的对象的查询集。

class ListAd(ListView):
    model = Ad
    template_name = 'filtered'
    queryset =  # here Im expecting to make a query based on the 'city' and 'category' chosen in previous view

如何将城市和类别参数传递给ListAd 视图,以便我可以在查询集中使用它们?这是 ursl.py

urlpatterns = [

    path('list_new/<city>/<category>/', views.ListAd.as_view(), name='filtered'),

]

任何帮助将不胜感激。谢谢

【问题讨论】:

    标签: django django-views


    【解决方案1】:

    我认为这应该可行。

    class ListAd(ListView):
        model = Ad
        template_name = 'filtered'
        queryset = Ad.objects.all()
        
        def get_queryset(self):
            queryset = super(ListAd, self).get_queryset()
            queryset = queryset.filter(city=self.kwargs["city"], category=self.kwargs["category"])
            return queryset
    

    【讨论】:

      猜你喜欢
      • 2013-06-29
      • 1970-01-01
      • 2013-12-05
      • 1970-01-01
      • 2017-08-31
      • 2014-10-22
      • 1970-01-01
      • 1970-01-01
      • 2013-10-22
      相关资源
      最近更新 更多