Samuel
Samuel

Reputation: 41

Django Class Based Views keep url parameters in session

I have a django listview working fine.

Its receive url parameters to filter data. Its paginated.

Now, I want to maintain these data along the user session. (page number and url parameters).

Example:

When I return to product list view, I whant to keep the search argument 'foo' and selected page 2.

What is the better way to do this?

I'm using Django 2.0.6

Models.py

class Product(models.Model):
    name= models.CharField(_('name'), max_length=150)
    price = models.DecimalField(max_digits=10, decimal_places=2, default=0.0)

Views.py

class ProductList(ListView):
    model = Product
    paginated_by = 10

    def get_queryset(self):

        queryset = Product.objects.all()

        name = self.request.GET.get('name', None)
        if name:
            queryset = queryset.filter(name__icontains=name)

        return queryset

Urls.py

path('products/', views.ProductList.as_view(), name='product_list'),

Upvotes: 3

Views: 2296

Answers (2)

Lucas B
Lucas B

Reputation: 2528

One common trick I use to do this is to use GET parameters and save directly the entire url in session (it saves time compared to saving each individual parameter individually)

class ProductList(ListView):
    model = Product
    paginated_by = 10

    def get_queryset(self):

        self.request.session['saved_product_list_url'] = self.request.get_full_path()
        ....


Then you can use it like this in templates :

<a href="{% if request.session.saved_product_list_url %}{{ request.session.saved_product_list_url }}{% else %}{% url 'product_list' %}{% endif %}">product list</a>

Or like this in views :

saved_product_list_url = self.request.session.get('saved_product_list_url')
if saved_product_list_url:
    return redirect(saved_product_list_url)
else:
    return redirect('product_list')

Also in your filter form you should add a "reset filters" like this :

<a href="{% url 'product_list' %}">reset filters</a>

Upvotes: 0

Rajat Jain
Rajat Jain

Reputation: 1415

For this you have to put the URL as a get request so that you can fetch the get values form the URL and use them in your filter to maintain your selection like:

url/?variable=value

Then in your Django view, you can access this by request.GET.get('variable') and pass this as the context in your HTML render page then use that variable in your filter selection.

Setting variable in session:

For setting the variable in the session you can set it by:

request.session['variable'] = 'value' 

and this value can be retrieve by:

if 'variable' in request.session:
    variable1 = request.session['variable']

You can refer this docs.

Upvotes: 4

Related Questions