class UserInfoView(LoginRequiredMixin, View):'''用户中心-信息页'''def get(self, request):'''显示'''# Django会给request对象添加一个属性request.user# 如果用户未登录->user是AnonymousUser类的一个实例对象# 如果用户登录->user是User类的一个实例对象# request.user.is_authenticated()# 获取用户的个人信息user = request.useraddress = Address.objects.get_default_address(user)# 获取用户的历史浏览记录# from redis import StrictRedis# sr = StrictRedis(host='172.16.179.130', port='6379', db=9)con = get_redis_connection('default')history_key = 'history_%d'%user.id# 获取用户最新浏览的5个商品的idsku_ids = con.lrange(history_key, 0, 4) # [2,3,1]# 从数据库中查询用户浏览的商品的具体信息# goods_li = GoodsSKU.objects.filter(id__in=sku_ids)## goods_res = []# for a_id in sku_ids:# for goods in goods_li:# if a_id == goods.id:# goods_res.append(goods)# 遍历获取用户浏览的商品信息goods_li = []for id in sku_ids:goods = GoodsSKU.objects.get(id=id)goods_li.append(goods)# 组织上下文context = {'page':'user','address':address,'goods_li':goods_li}# 除了你给模板文件传递的模板变量之外,django框架会把request.user也传给模板文件return render(request, 'user_center_info.html', context)
其中静态文件user_center_info.html中如下:
<h3 class="common_title2">最近浏览</h3><div class="has_view_list"><ul class="goods_type_list clearfix">{% for goods in goods_li %}<li><a href="detail.html"><img src="{{ goods.image.url }}"></a><h4><a href="detail.html">{{ goods.name }}</a></h4><div class="operate"><span class="prize">¥{{ goods.price }}</span><span class="unit">{{ goods.price }}/{{ goods.unite }}</span><a href="#" class="add_goods" title="加入购物车"></a></div></li>{% empty %}无历史浏览记录{% endfor %}</ul></div>
相关模块代码:
商品模型类中goods–models.py
class GoodsSKU(BaseModel):'''商品SKU模型类'''status_choices = ((0, '下线'),(1, '上线'),)type = models.ForeignKey('GoodsType', verbose_name='商品种类')goods = models.ForeignKey('Goods', verbose_name='商品SPU')name = models.CharField(max_length=20, verbose_name='商品名称')desc = models.CharField(max_length=256, verbose_name='商品简介')price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='商品价格')unite = models.CharField(max_length=20, verbose_name='商品单位')image = models.ImageField(upload_to='goods', verbose_name='商品图片')stock = models.IntegerField(default=1, verbose_name='商品库存')sales = models.IntegerField(default=0, verbose_name='商品销量')status = models.SmallIntegerField(default=1, choices=status_choices, verbose_name='商品状态')
django-redis获取redis链接
# Django的缓存配置
CACHES = {"default": {"BACKEND": "django_redis.cache.RedisCache","LOCATION": "redis://172.16.179.130:6379/9","OPTIONS": {"CLIENT_CLASS": "django_redis.client.DefaultClient",}}
}