0

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.

1 Answer 1

0

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)
2
  • Thanks bro ! Just curious, is there a better way to do what I was trying to do ? Sep 15, 2021 at 12:45
  • I'd do it with a QueryString parameter like so: In your url you append ?order=title for example. And in your view you can get that parameter with: sort_by = request.GET.get('order', '-last_edited'). Note that the second argument is the default if none is supplied. There is no need to do a POST request for that.
    – lucutzu33
    Sep 15, 2021 at 13:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.