I have a django listview working fine.
我有一个django listview正常工作。
Its receive url parameters to filter data. Its paginated.
它接收url参数来过滤数据。它的分页。
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.
当我返回产品列表视图时,我想保留搜索参数'foo'并选择第2页。
What is the better way to do this?
有什么更好的方法呢?
I'm using Django 2.0.6
我正在使用Django 2.0.6
Models.py
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
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
Urls.py
path('products/', views.ProductList.as_view(), name='product_list'),
0
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作为get请求,以便您可以从URL中获取get值并在过滤器中使用它们来维护您的选择,如:
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.
然后在Django视图中,您可以通过request.GET.get('variable')访问它,并将其作为HTML呈现页面中的上下文传递,然后在过滤器选择中使用该变量。
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.
你可以参考这个文档。
本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.silva-art.net/blog/2018/06/30/ba15425dbf045cff255c3c32eb2540ae.html。