Django формы очищенные_данные
Я хочу создать функциональность sort_by в моем приложении django и для этого я попробовал следующий способ. Первый шаг: forms.py
class SortForm(forms.Form):
CHOICES = [
('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)
<
def index(request):
################### Default, when form is not filled #################
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['ordering']
if sort_by == 'latest':
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')
context = {
'notes' : notes,
'form' : form,
}
return render(request, 'notes/index.html', context)
<
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
<
Вы не должны перенаправлять. Перенаправление заставляет клиента делать GET-запрос, поэтому request.method == 'POST'
будет False и ваш заказ не будет работать.
def index(request):
################### Default, when form is not filled #################
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['ordering']
if sort_by == 'latest':
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')
# Remove this line
return redirect('index')
context = {
'notes' : notes,
'form' : form,
}
return render(request, 'notes/index.html', context)