[Answered ]-How to take value from Django form?

1👍

You have to assign data to your form. See Bound and unbound forms

form = sortChoice(request.POST or request.GET)

After call form.is_valid(), you will be able to access cleaned_data.

And then your code is something like this:

@login_required(login_url = 'login')
def vacancyListView(request):
    searchQueryNavbar = request.GET.get('search_navbar', '')
    searchQueryVLpage = request.GET.get('search_vlpage', '')
    form = sortChoice(request.POST or request.GET)
    if searchQueryNavbar or searchQueryVLpage:
        if searchQueryNavbar:
            searchQuery = searchQueryNavbar
        else:
            searchQuery = searchQueryVLpage
        if form.is_valid():
            selected = form.cleaned_data.get("choice")
            if selected == 'sbp':
                queryset = Vacancy.objects.filter(Q(name__icontains = searchQuery) | Q(salary__icontains = searchQuery) | Q(competences__icontains = searchQuery)).order_by('-viewsAmount')
            if selected == 'sbd':
                queryset = Vacancy.objects.filter(Q(name__icontains = searchQuery) | Q(salary__icontains = searchQuery) | Q(competences__icontains = searchQuery)).order_by('-creationDate')
    else:
        queryset = Vacancy.objects.all().order_by('-viewsAmount')
    context = {
        'objectList':queryset,
        'form':form
    }
    return render(request, "vacancyList.html", context)

I would change the choice keys as following:

CHOICES = [
    ('creationDate', 'Сортировать по дате'),
    ('viewsAmount', 'Сортировать по популярности')
]

then you don’t have to use if else and do like this:

queryset = Vacancy.objects.filter(
    Q(name__icontains = searchQuery) | Q(salary__icontains = searchQuery) | Q(competences__icontains = searchQuery)
).order_by('-%s' % form.cleaned_data.get("choice"))
👤NKSM

Leave a comment