Django: Search form in Class Based ListView

前端 未结 7 2163
遥遥无期
遥遥无期 2020-12-04 13:22

I am trying to realize a Class Based ListView which displays a selection of a table set. If the site is requested the first time, the dataset should be displaye

7条回答
  •  旧时难觅i
    2020-12-04 14:01

    Well, I think that leaving validation to form is nice idea. Maybe not worth it in this particular case, because it is very simple form - but for sure with more complicated one (and maybe yours will grow also), so I would do something like:

    class ProfileList(ListView):
        model = Profile
        form_class = ProfileSearchForm
        context_object_name = 'profiles'
        template_name = 'pages/profile/list_profiles.html'
        profiles = []
    
    
        def get_queryset(self):
            form = self.form_class(self.request.GET)
            if form.is_valid():
                return Profile.objects.filter(name__icontains=form.cleaned_data['name'])
            return Profile.objects.all()
    

提交回复
热议问题