Issue
I want to create a sort_by functionality in my django app and for that I tried the following way. First step: 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)
Then views.py:
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)
models.py just in case:
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
It doesn't do anything when the form submit button is pressed and refreshes the index page with the default lookup defined above.
Solution
You must not redirect. Redirecting makes the client do a GET request, so request.method == 'POST'
will be False and your ordering will not work.
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)
Answered By - Ene Paul
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.