我想在我的django應用程式中創建一個sort_by功能,為此我嘗試了以下方法。 第一步: forms.py
class SortForm(forms.Form)。
選擇 = [...
('latest', 'Latest Notes')。
('oldest', 'Oldest Notes') 。
('alpha_descend', 'Alpahabetically(a to z)')。
('alpha_ascend', 'Alpahabetically (z to a)')。
]
ordering = forms.ChoiceField(widget=forms.RadioSelect, choices=CHOICES)
Then views.py:
def index(request)。
################### 默認,當表格沒有填寫#################。
notes = Note.objects.all().order_by('-last_edited')
form = SortForm()
if request.method == 'POST':
form = SortForm(request.POST)
if form.is_valid()。
sort_by = form.cleaned_data['order']
if sort_by == '最新'。
notes = Note.objects.all().order_by('-last_edited')
elif sort_by == 'oldest':
notes = Note.objects.all().order_by('last_edited')
elif sort_by == 'alpha_descend':
notes = Note.objects.all() .order_by('title')
elif sort_by == 'alpha_ascend':
notes = Note.objects.all().order_by('-title')
return redirect('index')
背景關系 = {
'notes' : notes,
'form' : form,
}
return render(request, 'note/index.html', context)
models.py 以防萬一:
class Note(models.Model)。
title = models.CharField(max_length=100)
body = models.TextField()
last_edited = models.DateTimeField(auto_now=True)
def __str__(self):
return self.title
當表單提交按鈕被按下時,它不做任何事情,而是用上面定義的default查找來重繪 索引頁。
uj5u.com熱心網友回復:
你一定不能重定向。重定向使客戶端做一個GET請求,所以request.method == 'POST'將是假的,你的訂購將不作業。
def index(request)。
################### 默認,當表格沒有填寫#################。
notes = Note.objects.all().order_by('-last_edited')
form = SortForm()
if request.method == 'POST':
form = SortForm(request.POST)
if form.is_valid()。
sort_by = form.cleaned_data['order']
if sort_by == '最新'。
notes = Note.objects.all().order_by('-last_edited')
elif sort_by == 'oldest':
notes = Note.objects.all().order_by('last_edited')
elif sort_by == 'alpha_descend':
notes = Note.objects.all() .order_by('title')
elif sort_by == 'alpha_ascend':
notes = Note.objects.all().order_by('-title')
# 洗掉這一行。
return redirect('index')
背景關系 = {
'notes' : notes,
'form' : form,
}
return render(request, 'note/index.html', context)
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/307466.html
標籤:
