I have Product
model:
class Product(models.Model):
title = models.CharField(max_length = 25)
description = models.TextField(blank = True, null = True)
price = models.IntegerField(default = 0)
image = models.ImageField(upload_to = 'products/images', null = True, blank = True)
image_url = models.URLField(null = True, blank = True)
created_at = models.DateTimeField(auto_now_add = True)
updated_at = models.DateTimeField(auto_now = True)
product_views = models.IntegerField(default = 0)
def __str__(self):
return self.title
class Meta:
ordering = ['title']
In each user view, I add one to product_views
. views.py
:
def product_detail_view(request, id):
if 'views' not in request.session:
request.session['views'] = []
arr = request.session['views']
# obj = Product.objects.get(id = id)
obj = get_object_or_404(Product, id = id)
if id not in arr:
arr.append(id)
request.session['views'] = arr
obj.product_views = obj.product_views 1
obj.save()
context = {
'object': obj,
}
return render(request, 'home/detail.html', context)
I set SESSION_COOKIE_AGE = 86400
in settings.py
. It works great. But there's one problem. In my app user can log in and after a day, he has to log in again. I wanted to add Remember me
checkbox to my log in, but here's problem. I can't set specific expire time for specific key. So I have to make my own 2nd Session Engine. I wrote this:
class ProductViews(models.Model):
product = models.ForeignKey(Product, on_delete = models.CASCADE, related_name = 'views', null = True, blank = True)
viewer = models.CharField(max_length = 36, null=True, blank=True) # Here, I can take IP if viewer isn't logged in
user = models.ForeignKey(User, on_delete = models.CASCADE, related_name = 'viewed_products', null = True, blank = True)
datetime = models.DateTimeField(default = django.utils.timezone.now)
I can check expiry time by this:
dateta = product_v.datetime
time_now = datetime.datetime.now(dateta.tzinfo) # current time
time_now = time_now - timedelta(days = 1)
if dateta < time_now: # check if stored time exceeds 1 day
product_v.delete(keep_parents = True)
I want to set SESSION_COOKIE_AGE
to 1 month, but it will affect the product_views
. It will not be able to count after 1 day, it will count after 1 month, that's not OK. I don't know, will it work so good as default DB Session Engine. Do you have any ideas about it? I will be thankfull for any help.
CodePudding user response:
I found the solution. There's no need to make 2nd Session Engine, because it will take much time, and it will be difficult to edit it by the time.
Here's a much easier way:
In middleware.py
I put:
class ViewsMiddleware:
def __init__(self, get_response):
self.get_response = get_response
# One-time configuration and initialization.
def __call__(self, request):
check_view(request)
response = self.get_response(request)
# Code to be executed for each request/response after
# the view is called.
return response
def check_view(request):
now = datetime.datetime.today()
print(request.session['viewed'])
print(request.session['views'])
if 'viewed' not in request.session or request.session['viewed'] != now.day:
request.session['viewed'] = now.day
request.session['views'] = []
obj, created = SiteView.objects.get_or_create(
current = f'{now.year} {now.month} {now.day}',
defaults = {'current': f'{now.year} {now.month} {now.day}', 'views': 1}
)
if not created:
obj.views = 1
obj.save()
And in details_view
(when product is viewed):
def detail_view(request, id):
obj = get_object_or_404(Product, pub_id = id)
if 'views' not in request.session:
request.session['views'] = []
arr = request.session['views']
if id not in arr:
arr.append(id)
request.session['views'] = arr
obj.product_views = obj.product_views 1
obj.save()
context = {
'title' : obj.title,
'object': obj,
}
return render(request, 'shop/products/detail.html', context)
I hope, it will you.