Esempio n. 1
0
    def post(self, request):
        # 获取用户传入的地址信息
        receiver = request.POST.get('receiver')
        addr = request.POST.get('addr')
        zip_code = request.POST.get('zip_code')
        phone = request.POST.get('phone')
        page = 'site'
        # 校验用户的信息的格式是否正确
        if not all([receiver, addr, zip_code, phone]):
            return render(request,
                          'user_center_site.html',
                          context={
                              'errmsg': '请填写全部内容',
                              'page': page
                          })
        # 校验手机号
        if not re.match(r'^1[34578][0-9]{9}$', phone):
            return render(request,
                          'user_center_site.html',
                          context={
                              'errmsg': '手机格式不正确',
                              'page': page
                          })
        # 获取当前用户
        user = request.user
        # 存储用户的地址信息
        Address.objects.create(user=user,
                               addr=addr,
                               receiver=receiver,
                               zip_code=zip_code,
                               phone=phone)

        return redirect(reverse('user:site'))
Esempio n. 2
0
    def get(self, request, token):
        # 解密获取要激活的邮箱
        serializer = Serializer(SECRET_KEY, 3600)
        try:

            info = serializer.loads(token)
            user_id = info['confirm']
            user = User.objects.get(id=user_id)
            user.is_active = 1
            user.save()
            return redirect(reverse('user:login'))
        except SignatureExpired as e:
            # 链接过期
            return HttpResponse('激活链接已失效')
Esempio n. 3
0
    def get(self, request, goods_id):
        """显示商品详情页"""
        # 判断传过来的商品有没有
        try:
            good = GoodsSKU.objects.get(id=goods_id)
        except GoodsSKU.DoesNotExist:
            return redirect(reverse('goods:index'))
        # 获取新品推荐

        new_goods = GoodsSKU.objects.filter(
            type=good.type).order_by('-create_time')[0:2:1]

        # 获取商品的品论信息
        good_orders = OrderGoods.objects.filter(sku=good).exclude(comment='')

        # 获取商品的分类信息
        types = GoodsType.objects.all()

        # 购物车的信息
        user = request.user
        cart_count = 0
        if user.is_authenticated:
            # 如果登录,获取数量
            conn = get_redis_connection('default')
            # 获取hash键值
            cart_key = 'cart_%d' % user.id
            # 通过hlen方法获取数量
            cart_count = conn.hlen(cart_key)

            # 添加用户的浏览记录
            conn = get_redis_connection('default')
            history_key = 'history_%d' % user.id
            # 移除表中与之相同的
            conn.lrem(history_key, 0, goods_id)
            # 把goods_id 插入到列表左侧
            conn.lpush(history_key, goods_id)
            # 只保存最新的五个历史记录
            conn.ltrim(history_key, 0, 4)

        return render(request,
                      'detail.html',
                      context={
                          'good': good,
                          'new_goods': new_goods,
                          'cart_count': cart_count,
                          'good_orders': good_orders,
                          'types': types
                      })
Esempio n. 4
0
    def get(self, request, goods_id):
        try:
            sku = GoodsSKU.objects.get(id=goods_id)
        except GoodsSKU.DoesNotExist:
            # 商品不存在
            return redirect(reverse('goods:index'))
        # 获取商品分类信息
        types = GoodsType.objects.all()
        # 获取商品用户评论
        sku_orders = OrderGoods.objects.filter(sku=sku).exclude(comment='')
        # 获取新品信息
        new_skus = GoodsSKU.objects.filter(
            type=sku.type).order_by('create_time')[:2]
        # 获取同一个SPU的其他规格商品
        samp_spu_skus = GoodsSKU.objects.filter(goods=sku.goods).exclude(
            id=goods_id)

        # 获取用户购物车中商品的数目
        user = request.user
        cart_count = 0
        if user.is_authenticated:
            # 用户已登录
            conn = get_redis_connection('default')
            cart_key = 'cart_%d' % user.id
            cart_count = conn.hlen(cart_key)
            # 添加用户的历史记录
            history_key = 'history_%d' % user.id
            # 移除列表中的goods_id
            conn.lrem(history_key, 0, goods_id)
            # 把goods_id插入到列表中
            conn.lpush(history_key, goods_id)
            # 只保存5条用户历史浏览记录
            conn.ltrim(history_key, 0, 4)
        context = {
            'sku': sku,
            'types': types,
            'sku_orders': sku_orders,
            'new_skus': new_skus,
            'samp_spu_skus': samp_spu_skus,
            'cart_count': cart_count
        }
        return render(request, 'detail.html', context)
Esempio n. 5
0
def create(request):
    form1 = ImagesForm(request.POST, request.FILES or None)
    form2 = AlbumForm(request.POST or None)
    if form2.is_valid() and form1.is_valid():
        image = form1.save(commit=False)
        image.product = Product.objects.get(pk=3)
        image.save()
        album = form2.save(commit=False)

        album.save()
        if 'next' in request.POST:
            next = request.POST['next']
        else:
            next = reverse('product_show')
        return HttpResponseRedirect(next)

    return render_to_response('album/create.html',
                              locals(),
                              context_instance = RequestContext(request),
                              )
Esempio n. 6
0
    def get_context_data(self, **kwargs):
        # get context data from TemplateView class
        context = super(JournalView, self).get_context_data(**kwargs)
        # check if we need to display some specific month
        if self.request.GET.get('month'):
            month = datetime.strptime(self.request.GET['month'],
                                      '%Y-%m-%d').date()
        else:
            # otherwise just displaying current month data
            today = datetime.today()
            month = date(today.year, today.month, 1)

        # calculate current, previous and next month details;
        # we need this for month navigation element in template
        next_month = month + relativedelta(months=1)
        prev_month = month - relativedelta(months=1)
        context['prev_month'] = prev_month.strftime('%Y-%m-%d')
        context['next_month'] = next_month.strftime('%Y-%m-%d')
        context['year'] = month.year
        context['month_verbose'] = month.strftime('%B')

        # we’ll use this variable in students pagination
        context['cur_month'] = month.strftime('%Y-%m-%d')

        #context['month_header'] = [
        #    {'day': 1, 'verbose': 'Пн'},
        #    {'day': 2, 'verbose': 'Вт'},
        #    {'day': 3, 'verbose': 'Ср'},
        #    {'day': 4, 'verbose': 'Чт'},
        #    {'day': 5, 'verbose': 'Пт'}]
        # prepare variable for template to generate
        # journal table header elements
        myear, mmonth = month.year, month.month
        number_of_days = monthrange(myear, mmonth)[1]
        context['month_header'] = [{
            'day':
            d,
            'verbose':
            day_abbr[weekday(myear, mmonth, d)][:2]
        } for d in range(1, number_of_days + 1)]

        # get all students from database
        if kwargs.get('pk'):
            queryset = [Student.objects.get(pk=kwargs['pk'])]
        else:
            current_group = get_current_group(self.request)
            if current_group:
                queryset = Student.objects.filter(student_group=current_group)
            else:
                queryset = Student.objects.order_by('last_name')

        # url to update student presence, for form post
        update_url = reverse('journal')

        # go over all students and collect data about presence
        # during selected month
        students = []
        for student in queryset:
            # TODO: витягуємо журнал для студента і
            # вибраного місяця
            # try to get journal object by month selected
            # month and current student
            try:
                journal = MonthJournal.objects.get(student=student, date=month)
            except Exception:
                journal = None

            # fill in days presence list for current student
            days = []
            for day in range(1, number_of_days + 1):
                days.append({
                    'day':
                    day,
                    'present':
                    journal
                    and getattr(journal, 'present_day{}'.format(day), False)
                    or False,
                    'date':
                    date(myear, mmonth, day).strftime('%Y-%m-%d'),
                })
            students.append({
                'fullname':
                '{} {}'.format(student.last_name, student.first_name),
                'days':
                days,
                'id':
                student.id,
                'update_url':
                update_url,
            })
        # apply pagination, 10 students per page
        context = paginate(students,
                           10,
                           self.request,
                           context,
                           var_name='students')

        # finally return updated context
        # with paginated students
        return context
Esempio n. 7
0
    def post(self, request):
        """用户注册校验"""
        register_form = RegisterForm(request.POST)

        if register_form.is_valid():
            # 获取前端数据
            username = register_form.cleaned_data['user_name']
            pwd = register_form.cleaned_data['pwd']
            cpwd = register_form.cleaned_data['cpwd']
            email = register_form.cleaned_data['email']
            allow = request.POST.get('allow')
            # 校验参数是否完整
            if not all([username, pwd, cpwd, email]):

                return render(request,
                              'register.html',
                              context={
                                  'errmsg': '请填写全部',
                                  'register_form': register_form
                              })
            # 校验用户是否存在
            try:
                use = User.objects.get(username=username)
            except Exception as e:
                use = None
            if use:
                return render(request,
                              'register.html',
                              context={
                                  'errmsg': '用户名已存在',
                                  'register_form': register_form
                              })
            # 校验密码是否正确
            if pwd != cpwd:
                return render(request,
                              'register.html',
                              context={
                                  'errmsg': '两次密码不一致',
                                  'register_form': register_form
                              })
            # 校验协议是否勾选
            if allow != 'on':
                return render(request,
                              'register.html',
                              context={
                                  'errmsg': '请勾选协议',
                                  'register_form': register_form
                              })
            # 检查邮箱不能重复
            try:
                user = User.objects.get(email=email)

            except Exception as e:
                user = None
            if user:
                return render(request,
                              'register.html',
                              context={
                                  'errmsg': '邮箱已经被注册',
                                  'register_form': register_form
                              })

            # 创建用户
            user = User.objects.create_user(username=username,
                                            password=pwd,
                                            email=email)
            # 上边的方法会自动将 is_active 改为1 也就是邮箱激活状态, 所以下边需要修改一下
            user.is_active = 0
            user.save()

            # 加密用户信息生成激活token
            serializer = Serializer(SECRET_KEY, 3600)
            info = {'confirm': user.id}
            token = serializer.dumps(info)
            # 获取到的数据是bytes类型的,需要解码
            token = token.decode()

            # 发送邮件
            send_active_email.delay(email, token, user.username)
            return redirect(reverse('user:login'))
        else:
            return render(request,
                          'register.html',
                          context={'register_form': register_form})
Esempio n. 8
0
 def get(self, request):
     logout(request)
     return redirect(reverse('goods:index'))
Esempio n. 9
0
    def post(self, request):
        form = LoginFrom(request.POST)
        if form.is_valid():
            username = form.cleaned_data['username']
            password = form.cleaned_data['pwd']
            if not all([username, password]):
                return render(request,
                              'login.html',
                              context={
                                  'form': form,
                                  'errmsg': '请填写完整'
                              })
            # django自带的用户验证方法
            # django自带的验证函数
            # user = authenticate(username=username, password=password)
            # if user is not None:
            #     if user.is_active:
            #         # 用户已激活
            #         # 自带的登录方法,并且会将session存储
            #         login(request, user)
            #         response = redirect(reverse('goods:index'))
            #         # 判断是否需要记住用户名
            #         remember = request.POST.get('remember')
            #         if remember == 'on':
            #             # 记住用户名
            #             response.set_cookie('username', username, max_age=7*24*3600)
            #         else:
            #             response.delete_cookie('username')
            #
            #         return response
            #     else:
            #         return render(request, 'login.html', context={
            #             'form': form,
            #             'errmsg': '用户邮箱未激活,请先激活再登录'
            #         })
            # else:
            #     return render(request, 'login.html', context={
            #         'form': form,
            #         'errmsg': '用户名或密码错误'
            #     })

            user = User.objects.filter(username=username).first()
            if user is None:
                return render(request,
                              'login.html',
                              context={'errmsg': '用户名不存在'})

            if user.check_password(password) is None:
                return render(request,
                              'login.html',
                              context={'errmsg': '用户名或密码错误'})
            if user.is_active == 0:
                return render(request,
                              'login.html',
                              context={'errmsg': '用户邮箱未激活,请先激活在登录'})

            # 自带的登录方法,并且会将session存储
            login(request, user)
            # 获取登录成功后要跳转的路径,因为使用的是自带的验证是否登陆的装饰器,如果没有登录会跳转到设置的登录页面
            # url后边会带上跳转前的路径,所以读取后边的路径,登陆后还跳转到之前的页面
            # 需要注意的后,前端form表单中的action不要写,  action不写会跳转到地址栏中的路径
            next_url = request.GET.get('next', reverse('goods:index'))

            response = redirect(next_url)
            # 判断是否需要记住用户名
            remember = request.POST.get('remember')
            if remember == 'on':
                # 记住用户名
                response.set_cookie('username',
                                    username,
                                    max_age=7 * 24 * 3600)
            else:
                response.delete_cookie('username')

            return response

        else:
            return render(request, 'login.html', context={'form': form})
Esempio n. 10
0
    def get(self, request, type_id, page):
        types = GoodsType.objects.all()
        # 获取种类信息
        try:
            type = GoodsType.objects.get(id=type_id)
        except GoodsType.DoesNotExist:
            # 种类不存在
            return redirect(reverse('goods:index'))
        # 获取排序的方式
        # 默认: ‘default’  价格:’price‘  销量:’hot‘

        sort = request.GET.get('sort')

        if sort == 'price':
            skus = GoodsSKU.objects.filter(type=type).order_by('price')
        elif sort == 'hot':
            skus = GoodsSKU.objects.filter(type=type).order_by('sales')
        else:
            sort = 'default'
            skus = GoodsSKU.objects.filter(type=type).order_by('id')

        # 对数据进行分页
        paginator = Paginator(skus, 2)  # 第一个参数:数据列表  第二个参数:每页显示几个

        # 获取传过来的页数
        try:
            page = int(page)
        except Exception as e:
            # 如果传过来的page数据不对,就自动为第一页
            page = 1
        # 如果传过来的页数超过本应的页数
        if page > paginator.num_pages:  # num_pages:获取总共有多少页
            page = 1
        # 获取第page页的实例对象
        sku_page = paginator.page(page)  # page(页数):获取这页的数据

        # todo:进行页码的控制,也马上最多显示5个页码
        # 获取购物车中的商品数量
        user = request.user
        cart_count = 0
        if user.is_authenticated:
            # 如果登录,获取数量
            conn = get_redis_connection('default')
            # 获取hash键值
            cart_key = 'cart_%d' % user.id
            # 通过hlen方法获取数量
            cart_count = conn.hlen(cart_key)
        # 获取新品推荐

        new_goods = GoodsSKU.objects.filter(
            type=type).order_by('-create_time')[0:2:1]
        return render(request,
                      'list.html',
                      context={
                          "cart_count": cart_count,
                          'sku_page': sku_page,
                          'sort': sort,
                          'type': type,
                          'new_goods': new_goods,
                          'types': types
                      })