Django 表单 cleaned_data

Django forms cleaned_data

我想在我的 Django 应用程序中创建一个 sort_by 功能,为此我尝试了以下方法。 第一步: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)

然后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 以防万一:

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 查找刷新索引页面时,它不执行任何操作。

您不得重定向。重定向使客户端执行 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)