Class Based ListView
はテーブルセットの選択を表示しています。サイトが初めて要求された場合は、データセットが表示されます。私はPOSTの提出を好むだろうが、GETもうまくいきます。Django:クラスベースのListViewの検索フォーム
これは問題です。これはfunction based views
で扱いやすくなりましたが、クラスベースのビューでは頭がおかしくなりません。
私の問題は、クラスベースのビューの制限された理解に起因するさまざまなエラーが発生することです。私は様々なドキュメントを読んできましたが、直接クエリ要求のビューを理解していますが、クエリステートメントにフォームを追加するとすぐに、別のエラーが発生します。以下のコードでは、ValueError: Cannot use None as a query value
が届きます。
フォームエントリに応じてクラスベースのListViewのベストプラクティスワークフローは何ですか(それ以外の場合はデータベース全体を選択します)。
これは私のサンプルコードです:
models.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
forms.py
class ProfileSearchForm(forms.Form):
name = forms.CharField(required=False)
views.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))
質問:フォーム提出に基づいてクエリセットから値を表示しようとしていますか? –
はい、それが目標でした。 – neurix
この一般的なmixinアプローチを見てみましょう: http://stackoverflow.com/questions/7011773/how-to-create-a-filter-form-for-a-class-based-generic-object- list-in-django –