D
D
Demian12020-05-29 19:01:07
Django
Demian1, 2020-05-29 19:01:07

How to convert FBV to CBV?

I just started learning django and in all books and in the docs, presentation examples are mostly written with functions. I decided to study the classes and rewrite the last "project"
The essence of the question: I can not rewrite the product sorting form

def product_list(request):
    products = Product.objects.filter(available=True)
    form = ArticlesFilterForm(request.GET)
    if form.is_valid():
        if form.cleaned_data['ordering']:
            products = products.order_by(form.cleaned_data['ordering'])
                                 
    return render(request, 'shop/product/list.html',  {'products': products, 
                        'form': form})


#Получается что-то типа такого
class ProductsView(ListView):
    model = Product
    context_object_name = 'product_list'
    template_name = 'shop/product_list.html'
    form = ArticlesFilterForm

    def get_queryset(self):
        form = self.form(self.request.GET)
        if form.is_valid():
            if form.cleaned_data['ordering']:
                product_list = product_list.prder_by(form.cleaned_data['ordering'])

    def get_context_data(self, *args, **kwargs):
        context = super().get_context_data(*args, **kwargs)
        context['product_list'] = Product.objects.all()
        context['form'] = ArticlesFilterForm
        return context


When I press sort it gives an error ( local variable 'product_list' referenced before assignment )

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
tema_sun, 2020-05-29
@Demian1

I would do it in get_ordering, not get_qureyset ( https://docs.djangoproject.com/en/3.0/ref/class-ba...
But to answer exactly your question, you don't have a queryset "product_list" defined which you are trying to sort.I
did not check, but I think you can fix it like this:

def get_queryset(self):
        qs = super().get_queryset()
        form = self.form(self.request.GET)
        if form.is_valid():
            if form.cleaned_data['ordering']:
                qs= qs.order_by(form.cleaned_data['ordering'])
        return qs

D
Demian1, 2020-05-29
@Demian1

Thanks for the answer, but I just solved the problem, it was necessary in the condition instead of the product_list variable, just return the object

if form.cleaned_data['ordering']:
                return Product.objects.order_by(form.cleaned_data['ordering'])
            return Product.objects.all()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question