我正在尝试实现一个Class Based ListView
显示一组表集的选择。如果第一次请求该站点,则应显示数据集。我更喜欢 POST 提交,但 GET 也可以。
这是一个很容易处理的问题function based views
,但是对于基于类的视图,我很难理解。
我的问题是我得到了各种各样的错误,这是由于我对基于分类的视图的理解有限造成的。我已阅读各种文档,并且了解直接查询请求的视图,但是一旦我想向查询语句添加表单,就会遇到不同的错误。对于下面的代码,我收到一个ValueError: Cannot use None as a query value
.
根据表单条目(否则选择整个数据库),基于类的 ListView 的最佳实践工作流程是什么?
这是我的示例代码:
模型.py
class Profile(models.Model):
name = models.CharField(_('Name'), max_length=255)
def __unicode__(self):
return '%name' % {'name': self.name}
@staticmethod
def get_queryset(params):
date_created = params.get('date_created')
keyword = params.get('keyword')
qset = Q(pk__gt = 0)
if keyword:
qset &= Q(title__icontains = keyword)
if date_created:
qset &= Q(date_created__gte = date_created)
return qset
表格.py
class ProfileSearchForm(forms.Form):
name = forms.CharField(required=False)
视图.py
class ProfileList(ListView):
model = Profile
form_class = ProfileSearchForm
context_object_name = 'profiles'
template_name = 'pages/profile/list_profiles.html'
profiles = []
def post(self, request, *args, **kwargs):
self.show_results = False
self.object_list = self.get_queryset()
form = form_class(self.request.POST or None)
if form.is_valid():
self.show_results = True
self.profiles = Profile.objects.filter(name__icontains=form.cleaned_data['name'])
else:
self.profiles = Profile.objects.all()
return self.render_to_response(self.get_context_data(object_list=self.object_list, form=form))
def get_context_data(self, **kwargs):
context = super(ProfileList, self).get_context_data(**kwargs)
if not self.profiles:
self.profiles = Profile.objects.all()
context.update({
'profiles': self.profiles
})
return context
下面我添加了完成这项工作的 FBV。如何将此功能转换为 CBV? 在基于函数的视图中似乎很简单,但在基于类的视图中却不是。
def list_profiles(request):
form_class = ProfileSearchForm
model = Profile
template_name = 'pages/profile/list_profiles.html'
paginate_by = 10
form = form_class(request.POST or None)
if form.is_valid():
profile_list = model.objects.filter(name__icontains=form.cleaned_data['name'])
else:
profile_list = model.objects.all()
paginator = Paginator(profile_list, 10) # Show 10 contacts per page
page = request.GET.get('page')
try:
profiles = paginator.page(page)
except PageNotAnInteger:
profiles = paginator.page(1)
except EmptyPage:
profiles = paginator.page(paginator.num_pages)
return render_to_response(template_name,
{'form': form, 'profiles': suppliers,},
context_instance=RequestContext(request))