Django forms cleaned_data

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

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published