def register(request): ctx = {} ctx.update(csrf(request)) ctx['system_para'] = get_system_parameters() ctx['menu_products'] = get_menu_products() ctx['page_name'] = 'Regitser' ctx = add_captcha(ctx) #添加验证码 logger.debug('Enter register function.') if request.method == 'GET': #GET请求,直接返回页面 return render(request, System_Config.get_template_name() + '/register.html', ctx) else: form = register_form(request.POST) # 获取Post表单数据 if form.is_valid(): # 验证表单 myuser = MyUser.objects.create_user( username=None, email=form.cleaned_data['email'].lower(), password=form.cleaned_data['password'], first_name=form.cleaned_data['first_name'], last_name=form.cleaned_data['last_name']) return redirect('/user/login') else: logger.error('form is not valid') ctx['reg_result'] = _('Registration faild.') return render(request, System_Config.get_template_name() + '/register.html', ctx)
def payment(request, order_id): ctx = {} ctx['system_para'] = get_system_parameters() ctx['menu_products'] = get_menu_products() ctx['page_name'] = 'Payment' order = Order.objects.get(id=order_id) ctx['paypal_account'] = System_Config.objects.get(name='paypal_account').val ctx['item_name'] = 'Your order:' + str(order.order_number) + " in " + System_Config.objects.get( name='site_name').val ctx['custom'] = order.order_number # 向paypal传送本地订单编号 ctx['amount'] = order.order_amount ctx['return_url'] = System_Config.objects.get(name='base_url').val + "/order/show/" ctx['cancel_url'] = System_Config.objects.get(name='base_url').val + "/order/show/" ctx['notify_url'] = System_Config.objects.get(name='base_url').val + reverse('paypal-ipn') ctx['cmd'] = '_xclick' ctx['currency_code'] = System_Config.objects.get(name='default_currency').val ctx['charset'] = 'utf-8' ctx['rm'] = '1' paypal_env = 'sandbox' try: paypal_env = System_Config.objects.get(name='paypal_env').val except: logger.info( '"paypal_env" is not definded,use default value : "sandbox".Please set the system parameter paypal_env = live if you want to use the paypal live service.') if paypal_env == 'live': ctx['paypal_action_url'] = 'https://www.paypal.com/cgi-bin/websc' else: ctx['paypal_action_url'] = 'https://www.sandbox.paypal.com/cgi-bin/websc' return TemplateResponse(request, System_Config.get_template_name() + '/payment.html', ctx)
def login(request, tdk=None): ctx = {} ctx['system_para'] = get_system_parameters() ctx['menu_products'] = get_menu_products() ctx['page_name'] = 'Login' ctx = add_captcha(ctx) #添加验证码 customize_tdk(ctx, tdk) if request.method == 'GET': #GET请求,直接返回页面 if 'next' in request.GET: ctx['next'] = request.GET['next'] return TemplateResponse( request, System_Config.get_template_name() + '/login.html', ctx) else: ctx.update(csrf(request)) form = captcha_form(request.POST) # 获取Post表单数据 if 'next' in request.POST: next = request.POST['next'] ctx['next'] = next #if form.is_valid():# 验证表单,会自动验证验证码,(新版不要验证码了) myuser = auth.authenticate(username=request.POST['email'].lower(), password=request.POST['password']) return do_login(request, myuser, ctx)
def info(request): ctx = {} ctx.update(csrf(request)) ctx['system_para'] = get_system_parameters() ctx['menu_products'] = get_menu_products() if request.method == 'GET': #GET请求,直接返回页面 return render(request,System_Config.get_template_name() + '/user_info.html',ctx) else: logger.debug("Modify User Info") form = user_info_form(request.POST) # 获取Post表单数据 myuser = request.user if form.is_valid():# 验证表单 myuser.first_name = form.cleaned_data['first_name'] myuser.last_name = form.cleaned_data['last_name'] logger.debug(myuser.last_name) else: logger.debug('not validate') if 'changePassword' in request.POST: #需要更改密码 myuser.set_password(request.POST['password']) else: #不更改密码 logger.debug('not checked') myuser.save() return redirect('/user/info/?success=true')
def info(request): ctx = {} ctx.update(csrf(request)) ctx['system_para'] = get_system_parameters() ctx['menu_products'] = get_menu_products() if request.method == 'GET': #GET请求,直接返回页面 return TemplateResponse( request, System_Config.get_template_name() + '/user_info.html', ctx) else: logger.debug("Modify User Info") form = user_info_form(request.POST) # 获取Post表单数据 myuser = request.user if form.is_valid(): # 验证表单 myuser.first_name = form.cleaned_data['first_name'] myuser.last_name = form.cleaned_data['last_name'] logger.debug(myuser.last_name) else: logger.debug('not validate') if 'changePassword' in request.POST: #需要更改密码 myuser.set_password(request.POST['password']) else: #不更改密码 logger.debug('not checked') myuser.save() return redirect('/user/info/?success=true')
def view_index(request): ctx = {} ctx['system_para'] = get_system_parameters() ctx['menu_products'] = get_menu_products() ctx['page_name'] = 'Home' return render(request, System_Config.get_template_name() + '/index.html', ctx)
def payment(request,order_id): ctx = {} ctx['system_para'] = get_system_parameters() ctx['menu_products'] = get_menu_products() ctx['page_name'] = 'Payment' order = Order.objects.get(id=order_id) ctx['paypal_account'] = System_Config.objects.get(name='paypal_account').val ctx['item_name'] = 'Your order:' + str(order.order_number) + " in " + System_Config.objects.get(name='site_name').val ctx['custom'] = order.order_number #向paypal传送本地订单编号 ctx['amount'] = order.order_amount ctx['return_url'] = System_Config.objects.get(name='base_url').val + "/order/show/" ctx['cancel_url'] = System_Config.objects.get(name='base_url').val + "/order/show/" ctx['notify_url'] = System_Config.objects.get(name='base_url').val + reverse('paypal-ipn') ctx['cmd'] = '_xclick' ctx['currency_code'] = System_Config.objects.get(name='default_currency').val ctx['charset'] = 'utf-8' ctx['rm'] = '1' paypal_env = 'sandbox' try: paypal_env = System_Config.objects.get(name='paypal_env').val except: logger.info('"paypal_env" is not definded,use default value : "sandbox".Please set the system parameter paypal_env = live if you want to use the paypal live service.') if paypal_env == 'live': ctx['paypal_action_url'] = 'https://www.paypal.com/cgi-bin/websc' else: ctx['paypal_action_url'] = 'https://www.sandbox.paypal.com/cgi-bin/websc' return render(request,System_Config.get_template_name() + '/payment.html',ctx)
def reset_password(request): ctx = {} ctx['system_para'] = get_system_parameters() ctx['menu_products'] = get_menu_products() ctx['page_name'] = 'Reset Password' if request.method == 'GET': ctx['success_display'] = 'display:none;' ctx['form_display'] = '' try: #日期大小与比较要用 "日期字段名__gt=" 表示大于 reset_password = Reset_Password.objects.filter(expirt_time__gt=datetime.datetime.now()).get(email=request.GET['email'],validate_code=request.GET['validate_code'],is_active=True) ctx['email'] = reset_password.email ctx['validate_code'] = reset_password.validate_code return render(request,System_Config.get_template_name() + '/reset_password.html',ctx) except: raise Http404 #ctx['form_display'] = 'none' #ctx['reset_message'] = _('Can not find the password reset apply request.') else: try: reset_password = Reset_Password.objects.filter(expirt_time__gt=datetime.datetime.now()).get(email=request.POST['email'],validate_code=request.POST['validate_code'],is_active=True) myuser = MyUser.objects.get(email=reset_password.email) myuser.set_password(request.POST['password']) reset_password.is_active = False reset_password.save() myuser.save() ctx['success_display'] = '' ctx['form_display'] = 'display:none;' ctx['reset_message'] = _('The password has been reseted.') except: ctx['success_display'] = '' ctx['form_display'] = 'display:none;' ctx['reset_message'] = _('Opration faild.') return render(request,System_Config.get_template_name() + '/reset_password.html',ctx)
def forget_password(request): ctx = {} ctx['system_para'] = get_system_parameters() ctx['menu_products'] = get_menu_products() ctx['page_name'] = 'Forget Password' ctx = add_captcha(ctx) #添加验证码 if request.method == 'GET': ctx['form_display'] = '' ctx['success_display'] = 'display:none;' return render(request,System_Config.get_template_name() + '/forget_password.html',ctx) else: form = captcha_form(request.POST) # 获取Post表单数据 if form.is_valid(): ctx['form_display'] = 'display:none;' ctx.update(csrf(request)) s_uuid = str(uuid.uuid4()) reset_password = Reset_Password.objects.create(email=request.POST['email'],validate_code=s_uuid,apply_time=datetime.datetime.now(),expirt_time=(datetime.datetime.now() + datetime.timedelta(hours=24)),is_active=True) mail_ctx = {} mail_ctx['reset_url'] = System_Config.get_base_url() + "/user/reset-password?email=" + reset_password.email + "&validate_code=" + reset_password.validate_code my_send_mail(useage='reset_password',ctx=mail_ctx,send_to=reset_password.email,title=_('You are resetting you password in %(site_name)s .') % {'site_name':System_Config.objects.get(name='site_name').val}) ctx['apply_message'] = _('If there is an account associated with %(email_address)s you will receive an email with a link to reset your password.') % {'email_address':reset_password.email} ctx['success_display'] = '' else: ctx['apply_message'] = _('Please check your verify code.') return render(request,System_Config.get_template_name() + '/forget_password.html',ctx)
def view_wishlist(request): ctx = {} ctx['system_para'] = get_system_parameters() ctx['menu_products'] = get_menu_products() ctx['page_name'] = 'My Wishlist' if request.method == 'GET': wish_list = Wish.objects.filter(user=request.user) try: page_size = int( System_Config.objects.get(name='wish_list_page_size').val) except: logger.info( 'The system parameter [wish_list_page_size] is not setted,use the default value 5.' ) page_size = 5 wish_list, page_range, current_page = my_pagination( request, wish_list, display_amount=page_size) ctx['wish_list'] = wish_list ctx['page_range'] = page_range ctx['current_page'] = current_page return TemplateResponse( request, System_Config.get_template_name() + '/wish_list.html', ctx)
def view_cart(request): if 'cart_id' in request.COOKIES: cart_id = request.COOKIES["cart_id"] cart,created = Cart.objects.get_or_create(id=cart_id) else: if request.user.is_authenticated(): cart,object = Cart.objects.get_or_create(user=request.user) else: cart = Cart.objects.create(user=None) if request.is_ajax(): ret_dict = {} ret_dict['success'] = True ret_dict['item_type_count'] = cart.cart_products.all().count() from shopcart.serializer import serializer #serialized_cart = serializer(cart,datetime_format='string',output_type='dict',many=True) #先不返回购物车中商品信息 serialized_cart = serializer(cart,datetime_format='string',output_type='dict',many=False) #logger.debug(serialized_cart) ret_dict['cart'] = serialized_cart return JsonResponse(ret_dict) else: ctx = {} ctx['system_para'] = get_system_parameters() ctx['menu_products'] = get_menu_products() ctx['page_name'] = 'My Cart' if request.method =='GET': ctx['cart'] = cart response = render(request,System_Config.get_template_name() + '/cart_detail.html',ctx) response.set_cookie('cart_id',cart.id ,max_age = 3600*24*365) return response
def view_cart(request): if 'cart_id' in request.COOKIES: cart_id = request.COOKIES["cart_id"] cart, created = Cart.objects.get_or_create(id=cart_id) else: if request.user.is_authenticated(): cart, object = Cart.objects.get_or_create(user=request.user) else: cart = Cart.objects.create(user=None) if request.is_ajax(): ret_dict = {} ret_dict['success'] = True ret_dict['item_type_count'] = cart.cart_products.all().count() from shopcart.serializer import serializer # serialized_cart = serializer(cart,datetime_format='string',output_type='dict',many=True) # 先不返回购物车中商品信息 serialized_cart = serializer(cart, datetime_format='string', output_type='dict', many=False) # logger.debug(serialized_cart) ret_dict['cart'] = serialized_cart return JsonResponse(ret_dict) else: ctx = {} ctx['system_para'] = get_system_parameters() ctx['menu_products'] = get_menu_products() ctx['page_name'] = 'My Cart' if request.method == 'GET': ctx['cart'] = cart response = TemplateResponse(request, System_Config.get_template_name() + '/cart_detail.html', ctx) response.set_cookie('cart_id', cart.id, max_age=3600 * 24 * 365) return response
def view_index(request,tdk=None): ctx = {} ctx['system_para'] = get_system_parameters() ctx['menu_products'] = get_menu_products() if not tdk: try: cust = CustomizeURL.objects.get(name = '首页') if cust.is_customize_tdk: tdk = {} tdk['page_title'] = cust.page_name tdk['keywords'] = cust.keywords tdk['short_desc'] = cust.short_desc except Exception as err: tdk = None if tdk: customize_tdk(ctx,tdk) from .oauth import SocialSites, SocialAPIError socialsites = SocialSites() s = socialsites.get_site_object_by_name('wechat') ctx['oauth'] = s.authorize_url return TemplateResponse(request,System_Config.get_template_name() + '/index.html',ctx)
def view_blog_list(request): ctx = {} ctx['system_para'] = get_system_parameters() ctx['menu_products'] = get_menu_products() ctx['page_name'] = 'Blog' try: blog_list_page_size = System_Config.objects.get('blog_list_page_size') except: logger.debug('blog_list_page_size is not defined,use the default value 12.') blog_list_page_size = 12 if request.method =='GET': product_list = None if 'sort_by' in request.GET: if 'direction' in request.GET: if 'desc' == request.GET['direction']: article_list = Article.objects.filter(category=Article.ARTICLE_CATEGORY_BLOG).order_by(request.GET['sort_by']).reverse() else: article_list = Article.objects.filter(category=Article.ARTICLE_CATEGORY_BLOG).order_by(request.GET['sort_by']) else: article_list = Article.objects.filter(category=Article.ARTICLE_CATEGORY_BLOG).order_by(request.GET['sort_by']) else: article_list = Article.objects.filter(category=Article.ARTICLE_CATEGORY_BLOG) if 'page_size' in request.GET: logger.debug('the page_size has been detacted') article_list, page_range = my_pagination(request=request, queryset=article_list,display_amount=request.GET['page_size']) else: article_list, page_range = my_pagination(request=request, queryset=article_list,display_amount=blog_list_page_size) ctx['article_list'] = article_list ctx['page_range'] = page_range return render(request,System_Config.get_template_name() + '/blog_list.html',ctx)
def query_product_show(request): ctx = {} ctx['system_para'] = get_system_parameters() ctx['menu_products'] = get_menu_products() ctx['page_name'] = 'Product' if request.method == 'GET': query_condition = request.GET.get('query', '') logger.debug('Query_String is %s ' % query_condition) from django.db.models import Q product_list = Product.objects.filter( Q(name__icontains=query_condition)) #icontains是大小写不敏感的,contains是大小写敏感的 if 'page_size' in request.GET: product_list, page_range = my_pagination( request=request, queryset=product_list, display_amount=request.GET['page_size']) else: product_list, page_range = my_pagination(request=request, queryset=product_list) ctx['product_list'] = product_list ctx['page_range'] = page_range return render(request, System_Config.get_template_name() + '/product_list.html', ctx)
def contact_page(request): ctx = {} ctx['system_para'] = get_system_parameters() ctx['menu_products'] = get_menu_products() ctx['page_name'] = 'Contact us' return render(request,System_Config.get_template_name() + '/contact.html',ctx)
def register(request): ctx = {} ctx.update(csrf(request)) ctx['system_para'] = get_system_parameters() ctx['menu_products'] = get_menu_products() ctx['page_name'] = 'Regitser' ctx = add_captcha(ctx) #添加验证码 logger.debug('Enter register function.') if request.method == 'GET': #GET请求,直接返回页面 return TemplateResponse(request,System_Config.get_template_name() + '/register.html',ctx) else: form = register_form(request.POST) # 获取Post表单数据 if form.is_valid():# 验证表单 from .utils import get_remote_ip ip = get_remote_ip(request) myuser = MyUser.objects.create_user(username=None,email=form.cleaned_data['email'].lower(),password=form.cleaned_data['password'],first_name=form.cleaned_data['first_name'],last_name=form.cleaned_data['last_name']) myuser.reg_ip = ip myuser.last_ip = ip myuser.save() #触发用户注册成功的事件 signals.user_registration_success.send(sender='MyUser',user=myuser) #return redirect('/user/login') #准备登陆 myuser.password = form.cleaned_data['password'] return inner_login(request,myuser,ctx) else: logger.error('form is not valid') ctx['reg_result'] = _('Registration faild.') return TemplateResponse(request,System_Config.get_template_name() + '/register.html',ctx)
def detail(request, id): ctx = {} ctx['system_para'] = get_system_parameters() ctx['menu_products'] = get_menu_products() ctx['page_name'] = 'Blog' try: article = Article.objects.get(id=id) except: raise Http404 ctx['article'] = article template = '/article.html' if article.detail_template != '': if article.detail_template != 'USE_DEFAULT': template = '/custmize/' + article.detail_template logger.info('The template name is %s' % template) if request.method == 'GET': #正常访问,返回动态页面 return render(request, System_Config.get_template_name() + template, ctx) elif request.method == 'POST': #通过ajax访问,生成静态文件 content = render_to_string( System_Config.get_template_name() + template, ctx) result_dict = {} try: import codecs, os dir = 'www/' + article.folder dir_http = article.folder if not os.path.exists(dir): os.makedirs(dir) if not dir.endswith('/'): dir = dir + '/' if not dir_http.endswith('/'): dir_http = dir_http + '/' f = codecs.open(dir + article.static_file_name, 'w', 'utf-8') f.write(content) f.close() result_dict['success'] = True result_dict['message'] = _('File already generated.') result_dict['static_url'] = dir_http + article.static_file_name except Exception as err: logger.error('写文件失败。' + str(err)) result_dict['success'] = False result_dict['message'] = _('File generate failed.') finally: if f is not None: f.close() return JsonResponse(result_dict)
def check_out(request): ctx = {} ctx['system_para'] = get_system_parameters() ctx['menu_products'] = get_menu_products() ctx['page_name'] = 'Check Out' if request.method == 'POST': # 得到cart_product_id cart_product_id_list = request.POST.getlist('cart_product_id', []) # 添加快递选择 express_list = ExpressType.objects.filter(is_in_use=True).filter( is_delete=False) # 将各种方式的价格都计算出来 for e in express_list: e.price_infact = calc_shipping_fee(cart_product_id_list, e) ctx['express_list'] = express_list ctx['default_express'] = express_list[0] promotion_code = request.POST.get('promotion_code', '') prices, promotion = get_prices( cart_product_id_list=cart_product_id_list, express_type=ctx['default_express'], discount_code=promotion_code) ctx['product_list'] = prices['product_list'] ctx['sub_total'] = prices['sub_total'] ctx['shipping'] = prices['shipping'] ctx['discount'] = prices['discount'] ctx['total'] = prices['total'] # 找出用户的地址簿 myuser = request.user addresses_list = Address.objects.filter(user=myuser) if addresses_list: has_default = False for address in addresses_list: if address.is_default: logger.debug('Find a default address.') ctx['default_address'] = address has_default = True break if not has_default: # 随便给一个 logger.debug('Do not a default address.') ctx['default_address'] = addresses_list[0] return TemplateResponse( request, System_Config.get_template_name() + '/check_out.html', ctx) else: return redirect(reverse('cart_view_cart'))
def view_wishlist(request): ctx = {} ctx['system_para'] = get_system_parameters() ctx['menu_products'] = get_menu_products() ctx['page_name'] = 'My Wishlist' if request.method =='GET': wish_list = Wish.objects.filter(user=request.user) wish_list, page_range = my_pagination(request, wish_list,display_amount=5) ctx['wish_list'] = wish_list ctx['page_range'] = page_range return render(request,System_Config.get_template_name() + '/wish_list.html',ctx)
def contact_page(request, tdk=None): ctx = {} ctx['system_para'] = get_system_parameters() ctx['menu_products'] = get_menu_products() ctx['page_name'] = 'Contact us' customize_tdk(ctx, tdk) return TemplateResponse( request, System_Config.get_template_name() + '/contact.html', ctx)
def detail(request,id): ctx = {} ctx['system_para'] = get_system_parameters() ctx['menu_products'] = get_menu_products() ctx['page_name'] = 'Blog' try: article = Article.objects.get(id=id) except: raise Http404 ctx['article'] = article template = '/article.html' if article.detail_template != '': if article.detail_template != 'USE_DEFAULT': template = '/custmize/' + article.detail_template logger.info('The template name is %s' % template) if request.method =='GET': #正常访问,返回动态页面 return render(request,System_Config.get_template_name() + template, ctx) elif request.method == 'POST':#通过ajax访问,生成静态文件 content = render_to_string(System_Config.get_template_name() + template, ctx) result_dict = {} try: import codecs,os dir = 'www/' + article.folder dir_http = article.folder if not os.path.exists(dir): os.makedirs(dir) if not dir.endswith('/'): dir = dir + '/' if not dir_http.endswith('/'): dir_http = dir_http + '/' f = codecs.open(dir + article.static_file_name ,'w','utf-8') f.write(content) f.close() result_dict['success'] = True result_dict['message'] = _('File already generated.') result_dict['static_url'] = dir_http + article.static_file_name except Exception as err: logger.error('写文件失败。' + str(err)) result_dict['success'] = False result_dict['message'] = _('File generate failed.') finally: if f is not None: f.close() return JsonResponse(result_dict)
def list_order_remark(request, order_no): ctx = {} ctx['system_para'] = get_system_parameters() ctx['menu_products'] = get_menu_products() ctx['page_name'] = 'My Orders' remark_list = OrderRemark.objects.filter(order__order_number=order_no) if request.user.has_perm('shopcart.can_list_order_remark'): ctx['remark_list'] = remark_list else: ctx['remark_list'] = '' return HttpResponse(str(remark_list))
def list_order_remark(request, order_no): ctx = {} ctx['system_para'] = get_system_parameters() ctx['menu_products'] = get_menu_products() ctx['page_name'] = 'My Orders' remark_list = OrderRemark.objects.filter(order__order_number=order_no) if request.user.has_perm('shopcart.can_list_order_remark'): ctx['remark_list'] = remark_list else: ctx['remark_list'] = '' return HttpResponse(str(remark_list))
def address_list(request): ctx = {} ctx['system_para'] = get_system_parameters() ctx['menu_products'] = get_menu_products() ctx['page_name'] = 'Address Book' if request.method=='GET': myuser = request.user address_list = Address.objects.filter(user=myuser) ctx['address_list'] = address_list return render(request,System_Config.get_template_name() + '/address.html',ctx) else: raise Http404
def reset_password(request): ctx = {} ctx['system_para'] = get_system_parameters() ctx['menu_products'] = get_menu_products() ctx['page_name'] = 'Reset Password' if request.method == 'GET': ctx['success_display'] = 'display:none;' ctx['form_display'] = '' try: #日期大小与比较要用 "日期字段名__gt=" 表示大于 reset_password = Reset_Password.objects.filter( expirt_time__gt=datetime.datetime.now()).get( email=request.GET['email'], validate_code=request.GET['validate_code'], is_active=True) ctx['email'] = reset_password.email ctx['validate_code'] = reset_password.validate_code return TemplateResponse( request, System_Config.get_template_name() + '/reset_password.html', ctx) except: raise Http404 #ctx['form_display'] = 'none' #ctx['reset_message'] = _('Can not find the password reset apply request.') else: try: reset_password = Reset_Password.objects.filter( expirt_time__gt=datetime.datetime.now()).get( email=request.POST['email'], validate_code=request.POST['validate_code'], is_active=True) myuser = MyUser.objects.get(email=reset_password.email) myuser.set_password(request.POST['password']) reset_password.is_active = False reset_password.save() myuser.save() #触发用户重置密码成功的事件 signals.user_password_modify_success.send(sender='MyUser', user=myuser) ctx['success_display'] = '' ctx['form_display'] = 'display:none;' ctx['reset_message'] = _('The password has been reseted.') except: ctx['success_display'] = '' ctx['form_display'] = 'display:none;' ctx['reset_message'] = _('Opration faild.') return TemplateResponse( request, System_Config.get_template_name() + '/reset_password.html', ctx)
def address_list(request): ctx = {} ctx['system_para'] = get_system_parameters() ctx['menu_products'] = get_menu_products() ctx['page_name'] = 'Address Book' if request.method == 'GET': myuser = request.user address_list = Address.objects.filter(user=myuser) ctx['address_list'] = address_list return render(request, System_Config.get_template_name() + '/address.html', ctx) else: raise Http404
def inquiry_detail(request, id): ctx = {} ctx['system_para'] = get_system_parameters() ctx['menu_products'] = get_menu_products() ctx['page_name'] = 'My inquiry' if request.method == 'GET': try: inquiry = Inquiry.objects.get(id=id) except Exception as err: logger.error('Can not find order %s' % (id)) raise Http404 ctx['inquiry'] = inquiry return TemplateResponse(request, System_Config.get_template_name() + '/inquiry_view.html', ctx)
def view_blog_list(request): ctx = {} ctx['system_para'] = get_system_parameters() ctx['menu_products'] = get_menu_products() ctx['page_name'] = 'Blog' try: blog_list_page_size = System_Config.objects.get('blog_list_page_size') except: logger.debug( 'blog_list_page_size is not defined,use the default value 12.') blog_list_page_size = 12 if request.method == 'GET': product_list = None if 'sort_by' in request.GET: if 'direction' in request.GET: if 'desc' == request.GET['direction']: article_list = Article.objects.filter( category=Article.ARTICLE_CATEGORY_BLOG).order_by( request.GET['sort_by']).reverse() else: article_list = Article.objects.filter( category=Article.ARTICLE_CATEGORY_BLOG).order_by( request.GET['sort_by']) else: article_list = Article.objects.filter( category=Article.ARTICLE_CATEGORY_BLOG).order_by( request.GET['sort_by']) else: article_list = Article.objects.filter( category=Article.ARTICLE_CATEGORY_BLOG) if 'page_size' in request.GET: logger.debug('the page_size has been detacted') article_list, page_range = my_pagination( request=request, queryset=article_list, display_amount=request.GET['page_size']) else: article_list, page_range = my_pagination( request=request, queryset=article_list, display_amount=blog_list_page_size) ctx['article_list'] = article_list ctx['page_range'] = page_range return render(request, System_Config.get_template_name() + '/blog_list.html', ctx)
def order_detail(request,id): ctx = {} ctx['system_para'] = get_system_parameters() ctx['menu_products'] = get_menu_products() ctx['page_name'] = 'My Orders' if request.method == 'GET': try: order = Order.objects.get(id=id) except Exception as err: logger.error('Can not find order %s' % (id)) raise Http404 ctx['order'] = order return render(request,System_Config.get_template_name() + '/order_view.html',ctx)
def check_out(request): ctx = {} ctx['system_para'] = get_system_parameters() ctx['menu_products'] = get_menu_products() ctx['page_name'] = 'Check Out' if request.method == 'POST': # 得到cart_product_id cart_product_id_list = request.POST.getlist('cart_product_id', []) # 添加快递选择 express_list = ExpressType.objects.filter(is_in_use=True).filter(is_delete=False) # 将各种方式的价格都计算出来 for e in express_list: e.price_infact = calc_shipping_fee(cart_product_id_list, e) ctx['express_list'] = express_list ctx['default_express'] = express_list[0] promotion_code = request.POST.get('promotion_code', '') prices, promotion = get_prices(cart_product_id_list=cart_product_id_list, express_type=ctx['default_express'], discount_code=promotion_code) ctx['product_list'] = prices['product_list'] ctx['sub_total'] = prices['sub_total'] ctx['shipping'] = prices['shipping'] ctx['discount'] = prices['discount'] ctx['total'] = prices['total'] # 找出用户的地址簿 myuser = request.user addresses_list = Address.objects.filter(user=myuser) if addresses_list: has_default = False for address in addresses_list: if address.is_default: logger.debug('Find a default address.') ctx['default_address'] = address has_default = True break; if not has_default: # 随便给一个 logger.debug('Do not a default address.') ctx['default_address'] = addresses_list[0] return TemplateResponse(request, System_Config.get_template_name() + '/check_out.html', ctx) else: return redirect(reverse('cart_view_cart'))
def view_index(request, tdk=None): ctx = {} ctx['system_para'] = get_system_parameters() ctx['menu_products'] = get_menu_products() def get_all_top_menu(): top_menu_list = Menu.objects.filter(parent=None) return top_menu_list top_menu_list = get_all_top_menu() ctx['menu_list'] = top_menu_list if not tdk: try: cust = CustomizeURL.objects.get(name='首页') if cust.is_customize_tdk: tdk = {} tdk['page_title'] = cust.page_name tdk['keywords'] = cust.keywords tdk['short_desc'] = cust.short_desc except Exception as err: tdk = None if tdk: customize_tdk(ctx, tdk) # from .oauth import SocialSites, SocialAPIError # socialsites = SocialSites() # s = socialsites.get_site_object_by_name('facebook') # ctx['oauth'] = s.authorize_url # 判断网站服务是否到期 maturity_data = System_Config.objects.get( name='maturity_data').val # 获取到期时间 new_maturity_data = time.strptime(maturity_data, "%Y-%m-%d %H:%M:%S") # 转化为时间戳 new_maturity_data_time = time.mktime(new_maturity_data) now_time = int(time.time()) # 获取当前时间 if now_time - new_maturity_data_time >= 0: return TemplateResponse( request, System_Config.get_template_name() + '/index_error.html', ctx) else: return TemplateResponse( request, System_Config.get_template_name() + '/index.html', ctx)
def order_detail(request, id): ctx = {} ctx['system_para'] = get_system_parameters() ctx['menu_products'] = get_menu_products() ctx['page_name'] = 'My Orders' if request.method == 'GET': try: order = Order.objects.get(id=id) except Exception as err: logger.error('Can not find order %s' % (id)) raise Http404 ctx['order'] = order return render(request, System_Config.get_template_name() + '/order_view.html', ctx)
def login(request, login_user=None): ctx = {} ctx['system_para'] = get_system_parameters() ctx['menu_products'] = get_menu_products() ctx['page_name'] = 'Login' ctx = add_captcha(ctx) #添加验证码 if request.method == 'GET': #GET请求,直接返回页面 if 'next' in request.GET: ctx['next'] = request.GET['next'] return render(request, System_Config.get_template_name() + '/login.html', ctx) else: if login_user: myuser = auth.authenticate(username=login_user.email, password=login_user.password) else: ctx.update(csrf(request)) form = captcha_form(request.POST) # 获取Post表单数据 if 'next' in request.POST: next = request.POST['next'] ctx['next'] = next #if form.is_valid():# 验证表单,会自动验证验证码,(新版不要验证码了) myuser = auth.authenticate(username=request.POST['email'].lower(), password=request.POST['password']) if myuser is not None: auth.login(request, myuser) mycart = merge_cart(request) redirect_url = reverse('product_view_list') if 'next' in request.POST: if len(request.POST['next']) > 0: redirect_url = request.POST['next'] response = redirect(redirect_url) response.set_cookie('cart_id', mycart.id, max_age=3600 * 24 * 365) response.set_cookie('cart_item_type_count', mycart.cart_products.all().count(), max_age=3600 * 24 * 365) response.set_cookie('icetususer', myuser.email) return response else: ctx['login_result'] = _( 'Your account name or password is incorrect.') return render(request, System_Config.get_template_name() + '/login.html', ctx)
def check_out(request): ctx = {} ctx['system_para'] = get_system_parameters() ctx['menu_products'] = get_menu_products() ctx['page_name'] = 'Check Out' if request.method == 'POST': #得到cart_product_id cart_product_id_list = request.POST.getlist('cart_product_id', []) #添加快递选择 ctx['express_list'] = ExpressType.objects.all() ctx['default_express'] = ExpressType.objects.all()[0] prices = get_prices(cart_product_id_list=cart_product_id_list, express_type=ctx['default_express']) ctx['product_list'] = prices['product_list'] ctx['sub_total'] = prices['sub_total'] ctx['shipping'] = prices['shipping'] ctx['discount'] = prices['discount'] ctx['total'] = prices['total'] #找出用户的地址簿 myuser = request.user addresses_list = Address.objects.filter(user=myuser) if addresses_list: has_default = False for address in addresses_list: if address.is_default: logger.debug('Find a default address.') ctx['default_address'] = address has_default = True break if not has_default: #随便给一个 logger.debug('Do not a default address.') ctx['default_address'] = addresses_list[0] return render(request, System_Config.get_template_name() + '/check_out.html', ctx) else: return redirect(reverse('cart_view_cart'))
def remove_from_wishlist(request): ctx = {} ctx.update(csrf(request)) result_dict = {} ctx['system_para'] = get_system_parameters() ctx['menu_products'] = get_menu_products() if request.method =='POST': wish_to_be_delete = json.loads((request.body).decode()) try: wish = Wish.objects.get(id=wish_to_be_delete['id'],user=request.user) wish.delete() except: pass result_dict['success'] = True result_dict['message'] = _('Opration successful.') return JsonResponse(result_dict)
def remove_from_wishlist(request): ctx = {} ctx.update(csrf(request)) result_dict = {} ctx['system_para'] = get_system_parameters() ctx['menu_products'] = get_menu_products() if request.method =='POST': wish_to_be_delete = json.loads((request.body).decode()) try: wish = Wish.objects.get(id=wish_to_be_delete['id'],user=request.user) wish.delete() except: pass result_dict['success'] = True result_dict['message'] = _('Opration successful.') return JsonResponse(result_dict)
def forget_password(request): ctx = {} ctx['system_para'] = get_system_parameters() ctx['menu_products'] = get_menu_products() ctx['page_name'] = 'Forget Password' ctx = add_captcha(ctx) #添加验证码 if request.method == 'GET': ctx['form_display'] = '' ctx['success_display'] = 'display:none;' return render( request, System_Config.get_template_name() + '/forget_password.html', ctx) else: form = captcha_form(request.POST) # 获取Post表单数据 if form.is_valid(): ctx['form_display'] = 'display:none;' ctx.update(csrf(request)) s_uuid = str(uuid.uuid4()) reset_password = Reset_Password.objects.create( email=request.POST['email'], validate_code=s_uuid, apply_time=datetime.datetime.now(), expirt_time=(datetime.datetime.now() + datetime.timedelta(hours=24)), is_active=True) mail_ctx = {} mail_ctx['reset_url'] = System_Config.get_base_url( ) + "/user/reset-password?email=" + reset_password.email + "&validate_code=" + reset_password.validate_code my_send_mail( useage='reset_password', ctx=mail_ctx, send_to=reset_password.email, title=_('You are resetting you password in %(site_name)s .') % {'site_name': System_Config.objects.get(name='site_name').val}) ctx['apply_message'] = _( 'If there is an account associated with %(email_address)s you will receive an email with a link to reset your password.' ) % { 'email_address': reset_password.email } ctx['success_display'] = '' else: ctx['apply_message'] = _('Please check your verify code.') return render( request, System_Config.get_template_name() + '/forget_password.html', ctx)
def view_list(request): ctx = {} ctx['system_para'] = get_system_parameters() ctx['menu_products'] = get_menu_products() ctx['page_name'] = 'Product' if request.method == 'GET': product_list = None if 'sort_by' in request.GET: if 'direction' in request.GET: if 'desc' == request.GET['direction']: product_list = Product.objects.filter( is_publish=True).order_by( request.GET['sort_by']).reverse() else: product_list = Product.objects.filter( is_publish=True).order_by(request.GET['sort_by']) ctx['direction'] = request.GET['direction'] else: product_list = Product.objects.filter( is_publish=True).order_by(request.GET['sort_by']) else: logger.debug("all products") product_list = Product.objects.filter(is_publish=True) logger.debug("no sort_by") if 'page_size' in request.GET: page_size = request.GET['page_size'] else: try: page_size = int( System_Config.objects.get(name='product_page_size')) except: page_size = 12 product_list, page_range = my_pagination(request=request, queryset=product_list, display_amount=page_size) ctx['product_list'] = product_list ctx['page_range'] = page_range return render(request, System_Config.get_template_name() + '/product_list.html', ctx)
def show_order(request): logger.info('Start to show order.') ctx = {} ctx['system_para'] = get_system_parameters() ctx['menu_products'] = get_menu_products() ctx['page_name'] = 'My Orders' if request.method == 'GET': order_list = Order.objects.filter(user=request.user) try: order_list_page_size = System_Config.objects.get('order_list_page_size') except: logger.debug('order_list_page_size is not defined,use the default value 10.') order_list_page_size = 10 order_list, page_range = my_pagination(request, order_list,display_amount=order_list_page_size) ctx['order_list'] = order_list ctx['page_range'] = page_range return render(request,System_Config.get_template_name() + '/orders.html',ctx)
def contact_page(request, tdk=None): ctx = {} ctx['system_para'] = get_system_parameters() ctx['menu_products'] = get_menu_products() ctx['page_name'] = 'Contact us' def get_all_top_menu(): top_menu_list = Menu.objects.filter(parent=None) return top_menu_list top_menu_list = get_all_top_menu() ctx['menu_list'] = top_menu_list customize_tdk(ctx, tdk) return TemplateResponse( request, System_Config.get_template_name() + '/contact.html', ctx)
def view_cart(request): ctx = {} ctx['system_para'] = get_system_parameters() ctx['menu_products'] = get_menu_products() ctx['page_name'] = 'My Cart' if request.method =='GET': if 'cart_id' in request.COOKIES: cart_id = request.COOKIES["cart_id"] cart,created = Cart.objects.get_or_create(id=cart_id) else: if request.user.is_authenticated(): cart,object = Cart.objects.get_or_create(user=request.user) else: cart = Cart.objects.create(user=None) ctx['cart'] = cart response = render(request,System_Config.get_template_name() + '/cart_detail.html',ctx) response.set_cookie('cart_id',cart.id) return response
def view_wishlist(request): ctx = {} ctx['system_para'] = get_system_parameters() ctx['menu_products'] = get_menu_products() ctx['page_name'] = 'My Wishlist' if request.method =='GET': wish_list = Wish.objects.filter(user=request.user) try: page_size = int(System_Config.objects.get(name='wish_list_page_size').val) except: logger.info('The system parameter [wish_list_page_size] is not setted,use the default value 5.') page_size = 5 wish_list, page_range,current_page = my_pagination(request, wish_list,display_amount=page_size) ctx['wish_list'] = wish_list ctx['page_range'] = page_range ctx['current_page'] = current_page return TemplateResponse(request,System_Config.get_template_name() + '/wish_list.html',ctx)
def check_out(request): ctx = {} ctx['system_para'] = get_system_parameters() ctx['menu_products'] = get_menu_products() ctx['page_name'] = 'Check Out' if request.method == 'POST': #得到cart_product_id cart_product_id_list = request.POST.getlist('cart_product_id',[]) #添加快递选择 ctx['express_list'] = ExpressType.objects.all() ctx['default_express'] = ExpressType.objects.all()[0] prices = get_prices(cart_product_id_list=cart_product_id_list,express_type=ctx['default_express']) ctx['product_list'] = prices['product_list'] ctx['sub_total'] = prices['sub_total'] ctx['shipping'] = prices['shipping'] ctx['discount'] = prices['discount'] ctx['total'] = prices['total'] #找出用户的地址簿 myuser = request.user addresses_list = Address.objects.filter(user=myuser) if addresses_list: has_default = False for address in addresses_list: if address.is_default: logger.debug('Find a default address.') ctx['default_address'] = address has_default = True break; if not has_default: #随便给一个 logger.debug('Do not a default address.') ctx['default_address'] = addresses_list[0] return render(request,System_Config.get_template_name() + '/check_out.html',ctx) else: return redirect(reverse('cart_view_cart'))
def show_order(request): logger.info('Start to show order.') ctx = {} ctx['system_para'] = get_system_parameters() ctx['menu_products'] = get_menu_products() ctx['page_name'] = 'My Orders' if request.method == 'GET': order_list = Order.objects.filter(user=request.user) try: order_list_page_size = System_Config.objects.get('order_list_page_size') except: logger.debug('order_list_page_size is not defined,use the default value 10.') order_list_page_size = 10 order_list, page_range, current_page = my_pagination(request, order_list, display_amount=order_list_page_size) ctx['order_list'] = order_list ctx['page_range'] = page_range ctx['current_page'] = current_page return TemplateResponse(request, System_Config.get_template_name() + '/orders.html', ctx)
def view_index(request, tdk=None): ctx = {} ctx['system_para'] = get_system_parameters() ctx['menu_products'] = get_menu_products() def get_all_top_menu(): top_menu_list = Menu.objects.filter(parent=None) return top_menu_list top_menu_list = get_all_top_menu() ctx['menu_list'] = top_menu_list if not tdk: try: cust = CustomizeURL.objects.get(name='首页') if cust.is_customize_tdk: tdk = {} tdk['page_title'] = cust.page_name tdk['keywords'] = cust.keywords tdk['short_desc'] = cust.short_desc except Exception as err: tdk = None if tdk: customize_tdk(ctx, tdk) # from .oauth import SocialSites, SocialAPIError # socialsites = SocialSites() # s = socialsites.get_site_object_by_name('facebook') # ctx['oauth'] = s.authorize_url # 判断网站服务是否到期 maturity_data = System_Config.objects.get(name='maturity_data').val # 获取到期时间 new_maturity_data = time.strptime(maturity_data, "%Y-%m-%d %H:%M:%S") # 转化为时间戳 new_maturity_data_time = time.mktime(new_maturity_data) now_time = int(time.time()) # 获取当前时间 if now_time - new_maturity_data_time >= 0: return TemplateResponse(request, System_Config.get_template_name() + '/index_error.html', ctx) else: return TemplateResponse(request, System_Config.get_template_name() + '/index.html', ctx)
def register(request): ctx = {} ctx.update(csrf(request)) ctx['system_para'] = get_system_parameters() ctx['menu_products'] = get_menu_products() ctx['page_name'] = 'Regitser' ctx = add_captcha(ctx) #添加验证码 logger.debug('Enter register function.') if request.method == 'GET': #GET请求,直接返回页面 return TemplateResponse( request, System_Config.get_template_name() + '/register.html', ctx) else: form = register_form(request.POST) # 获取Post表单数据 if form.is_valid(): # 验证表单 from .utils import get_remote_ip ip = get_remote_ip(request) myuser = MyUser.objects.create_user( username=None, email=form.cleaned_data['email'].lower(), password=form.cleaned_data['password'], first_name=form.cleaned_data['first_name'], last_name=form.cleaned_data['last_name']) myuser.reg_ip = ip myuser.last_ip = ip myuser.save() #触发用户注册成功的事件 signals.user_registration_success.send(sender='MyUser', user=myuser) #return redirect('/user/login') #准备登陆 myuser.password = form.cleaned_data['password'] return inner_login(request, myuser, ctx) else: logger.error('form is not valid') ctx['reg_result'] = _('Registration faild.') return TemplateResponse( request, System_Config.get_template_name() + '/register.html', ctx)
def register(request): ctx = {} ctx.update(csrf(request)) ctx['system_para'] = get_system_parameters() ctx['menu_products'] = get_menu_products() ctx['page_name'] = 'Regitser' ctx = add_captcha(ctx) #添加验证码 logger.debug('Enter register function.') if request.method == 'GET': #GET请求,直接返回页面 return render(request,System_Config.get_template_name() + '/register.html',ctx) else: form = register_form(request.POST) # 获取Post表单数据 if form.is_valid():# 验证表单 myuser = MyUser.objects.create_user(username=None,email=form.cleaned_data['email'].lower(),password=form.cleaned_data['password'],first_name=form.cleaned_data['first_name'],last_name=form.cleaned_data['last_name']) return redirect('/user/login') else: logger.error('form is not valid') ctx['reg_result'] = _('Registration faild.') return render(request,System_Config.get_template_name() + '/register.html',ctx)
def view_cart(request): ctx = {} ctx['system_para'] = get_system_parameters() ctx['menu_products'] = get_menu_products() ctx['page_name'] = 'My Cart' if request.method == 'GET': if 'cart_id' in request.COOKIES: cart_id = request.COOKIES["cart_id"] cart, created = Cart.objects.get_or_create(id=cart_id) else: if request.user.is_authenticated(): cart, object = Cart.objects.get_or_create(user=request.user) else: cart = Cart.objects.create(user=None) ctx['cart'] = cart response = render( request, System_Config.get_template_name() + '/cart_detail.html', ctx) response.set_cookie('cart_id', cart.id) return response
def login(request,tdk=None): ctx = {} ctx['system_para'] = get_system_parameters() ctx['menu_products'] = get_menu_products() ctx['page_name'] = 'Login' ctx = add_captcha(ctx) #添加验证码 customize_tdk(ctx,tdk) if request.method == 'GET': #GET请求,直接返回页面 if 'next' in request.GET: ctx['next'] = request.GET['next'] return TemplateResponse(request,System_Config.get_template_name() + '/login.html',ctx) else: ctx.update(csrf(request)) form = captcha_form(request.POST) # 获取Post表单数据 if 'next' in request.POST: next = request.POST['next'] ctx['next'] = next #if form.is_valid():# 验证表单,会自动验证验证码,(新版不要验证码了) myuser = auth.authenticate(username = request.POST['email'].lower(), password = request.POST['password']) return do_login(request,myuser,ctx)
def login(request): ctx = {} ctx['system_para'] = get_system_parameters() ctx['menu_products'] = get_menu_products() ctx['page_name'] = 'Login' ctx = add_captcha(ctx) #添加验证码 if request.method == 'GET': #GET请求,直接返回页面 if 'next' in request.GET: ctx['next'] = request.GET['next'] return render(request,System_Config.get_template_name() + '/login.html',ctx) else: ctx.update(csrf(request)) form = captcha_form(request.POST) # 获取Post表单数据 if 'next' in request.POST: next = request.POST['next'] ctx['next'] = next #if form.is_valid():# 验证表单,会自动验证验证码,(新版不要验证码了) myuser = auth.authenticate(username = request.POST['email'].lower(), password = request.POST['password']) if myuser is not None: auth.login(request,myuser) mycart = merge_cart(request) redirect_url = reverse('product_view_list') if 'next' in request.POST: if len(request.POST['next']) > 0: redirect_url = request.POST['next'] response = redirect(redirect_url) response.set_cookie('cart_id',mycart.id) response.set_cookie('imycartuser',myuser.email) return response else: ctx['login_result'] = _('Your account name or password is incorrect.') return render(request,System_Config.get_template_name() + '/login.html',ctx)
def place_order(request): logger.info('Start to place order.') ctx = {} ctx['system_para'] = get_system_parameters() ctx['menu_products'] = get_menu_products() ctx['page_name'] = 'Place Order' if request.method == 'POST': logger.debug('address_id:' + str(request.POST['address_id'])) try: address = Address.objects.get(id=request.POST['address_id']) except: ctx['content'] = _('Address is not correct') return TemplateResponse(request, System_Config.get_template_name() + '/info_show.html', ctx) if address not in request.user.addresses.all(): # 如果这个地址不是这个用户的,报错 ctx['content'] = 'System Error.Please try again.' return TemplateResponse(request, System_Config.get_template_name() + '/info_show.html', ctx) # 金额 sub_total, shipping, discount, total, remark, express_type = request.POST['sub_total'], request.POST[ 'shipping'], request.POST['discount'], request.POST['total'], request.POST['remark'], request.POST[ 'express'] promotion_code = request.POST.get('promotion_code') cart_product_id = request.POST.getlist('cart_product_id', []) # logger.debug('>>>>>0:sub_total=' + str(sub_total)) try: express = ExpressType.objects.get(id=express_type) except Exception as err: logger.error('Can not find express_type %s. \n Error Message:%s' % (express_type, err)) ctx['content'] = 'System Error.Please try again.' return TemplateResponse(request, System_Config.get_template_name() + '/info_show.html', ctx) from .cart import get_prices prices, promotion = get_prices(cart_product_id_list=cart_product_id, express_type=express, discount_code=promotion_code) if abs(float(shipping) - float(prices['shipping'])) > 0.01: logger.error('Amount shipping check faild! Amount in client is [%s],but the server need [%s].' % ( shipping, prices['shipping'])) raise Exception('System error.Please try again.') if abs(float(discount) - float(prices['discount'])) > 0.01: logger.error('Amount discount check faild! Amount in client is [%s],but the server need [%s].' % ( discount, prices['discount'])) raise Exception('System error.Please try again.') if abs(float(total) - float(prices['total'])) > 0.01: logger.error('Amount total check faild! Amount in client is [%s],but the server need [%s].' % ( total, prices['total'])) raise Exception('System error.Please try again.') logger.info('Amount check success!') # 生成主订单 # logger.debug('>>>>>1') order = Order.objects.create(order_number=get_serial_number(), user=request.user, status=Order.ORDER_STATUS_PLACE_ORDER, country=address.country, province=address.province, city=address.city, district=address.district, address_line_1=address.address_line_1, address_line_2=address.address_line_2, first_name=address.first_name, last_name=address.last_name, zipcode=address.zipcode, tel=address.tel, mobile=address.mobile, email=request.user.email, products_amount=sub_total, shipping_fee=shipping, discount=discount, order_amount=total, to_seller=remark, express_type_name=express.name, promotion_code=promotion_code) # 如果有客户留言,则记录客户留言 remark = request.POST.get('cust_remark', '') if remark: remark_content = OrderCustRemark.objects.create(order=order, content=remark) for cp_id in cart_product_id: cp = Cart_Products.objects.get(id=cp_id) # amount_to_check = amount_to_check + cp.get_total() # 向主订单加入商品 # logger.debug('>>>>>5:product.id='+str(cp.product.id)) pa_id = None pa_name = '' pa_item_number = None if cp.product_attribute: pa_id = cp.product_attribute.id pa_name = cp.product_attribute.get_grouped_attribute_desc() pa_item_number = cp.product_attribute.sub_item_number op = Order_Products.objects.create(product_id=cp.product.id, product_attribute_id=pa_id, order=order, name=cp.product.name, short_desc=cp.product.short_desc, price=cp.get_product_price(), thumb=cp.product.thumb, image=cp.product.image, quantity=cp.quantity, product_attribute_name=pa_name, product_attribute_item_number=pa_item_number) # logger.debug('>>>>>6:op.id='+str(op.id)) # 20160614,考拉,加入了扣减库存的逻辑 if cp.product_attribute: product_attribute = cp.product_attribute product_attribute.quantity = product_attribute.quantity - cp.quantity if product_attribute.quantity < 0: ctx['content'] = 'The product "%s" is sold out.' % product_attribute.product.name ctx['backurl'] = '/cart/show/' return TemplateResponse(request, System_Config.get_template_name() + '/info_show.html', ctx) # raise Exception('The product "%s" is sold out.' % product_attribute.product.name) product_attribute.save() else: product = cp.product product.quantity = product.quantity - cp.quantity if product.quantity < 0: ctx['content'] = 'The product "%s" is sold out.' % product.name ctx['backurl'] = '/cart/show/' return TemplateResponse(request, System_Config.get_template_name() + '/info_show.html', ctx) # raise Exception('The product "%s" is sold out.' % product.name) product.save() # 删除购物车中商品 cp.delete() # logger.debug('>>>>>8:cp.delete') return redirect('/cart/payment/' + str(order.id))
def place_order(request): logger.info('Start to place order.') ctx = {} ctx['system_para'] = get_system_parameters() ctx['menu_products'] = get_menu_products() ctx['page_name'] = 'Place Order' if request.method == 'POST': logger.debug('address_id:' + str(request.POST['address_id'])) try: address = Address.objects.get(id=request.POST['address_id']) except: ctx['order_result'] = _('Address is not correct') return render(request,System_Config.get_template_name() + '/order_result.html',ctx) if address not in request.user.addresses.all(): #如果这个地址不是这个用户的,报错 ctx['order_result'] = 'System Error.Please try again.' return render(request,System_Config.get_template_name() + '/order_result.html',ctx) #金额 sub_total,shipping,discount,total,remark,express_type = request.POST['sub_total'],request.POST['shipping'],request.POST['discount'],request.POST['total'],request.POST['remark'],request.POST['express'] logger.debug('>>>>>0:sub_total=' + str(sub_total)) #生成主订单 logger.debug('>>>>>1') order = Order.objects.create(order_number=get_serial_number(),user=request.user,status=Order.ORDER_STATUS_PLACE_ORDER,country=address.country,province=address.province,city=address.city,district=address.district,address_line_1=address.address_line_1, address_line_2=address.address_line_2,first_name=address.first_name,last_name=address.last_name,zipcode=address.zipcode,tel=address.tel,mobile=address.mobile,email=request.user.email, products_amount = sub_total,shipping_fee=shipping,discount=discount,order_amount=total,to_seller=remark,express_type_name = ExpressType.objects.get(id=express_type).name) logger.debug('>>>>>2:order.id='+str(order.id)) cart_product_id = request.POST.getlist('cart_product_id',[]) logger.debug('>>>>>3:cart_product_id='+str(cart_product_id)) #计算汇总金额 amount_to_check = 0.00 for cp_id in cart_product_id: cp = Cart_Products.objects.get(id=cp_id) amount_to_check = amount_to_check + cp.get_total() #向主订单加入商品 logger.debug('>>>>>5:product.id='+str(cp.product.id)) op = Order_Products.objects.create(product_id=cp.product.id,product_attribute=cp.product_attribute,order=order,name=cp.product.name,short_desc=cp.product.short_desc,price=cp.get_product_price(), thumb=cp.product.thumb,image=cp.product.image,quantity=cp.quantity) logger.debug('>>>>>6:op.id='+str(op.id)) # 20160614,考拉,加入了扣减库存的逻辑 if cp.product_attribute: product_attribute = cp.product_attribute product_attribute.quantity = product_attribute.quantity - cp.quantity #if product_attribute.quantity < 0: # raise Exception('QUANTITY_INVALID|The product is sold out.') product_attribute.save() else: product = cp.product product.quantity = product.quantity - cp.quantity #if product.quantity < 0: # raise Exception('QUANTITY_INVALID|The product is sold out.') product.save() #删除购物车中商品 cp.delete() logger.debug('>>>>>8:cp.delete') #TODO:校验总金额是否正确,不正确则抛出异常 logger.debug('>>>>>9:amount_to_check=' + str(amount_to_check)) if abs(amount_to_check-float(sub_total)) > 0.01: #浮点数比较,没法直接用 == raise Exception('System error.Please try again.') return redirect('/cart/payment/' + str(order.id))
def address(request,method,id=''): ctx = {} ctx['system_para'] = get_system_parameters() ctx['menu_products'] = get_menu_products() ctx['page_name'] = 'Address Book' result_dict = {} result = False message = 'System Error' if request.method == 'POST': address_id = request.POST.get('address_id','') logger.debug('The address id is %s.' % (address_id)) #用途的拼装方法 useage = request.POST['first_name'] + ' ' + request.POST['last_name'] + '@' + request.POST['city'] #20160525,倪肖勇加入地址数量控制,有一个系统参数 common_user_address_limit,用来控制普通用户的地址数量,如果参数没有设置,默认5条 address_count = Address.objects.filter(user=request.user).count() logger.debug('The address count of this user is:%s' % (address_count)) limit = 5 try: limit = int(System_Config.objects.get('common_user_address_limit')) except: logger.info('common_user_address_limit is not setted. use default value 5.') can_add = (True if limit > address_count else False) logger.debug('Address can add ? %s' % (can_add)) if method == 'add' or method == 'modify': if not address_id: if can_add: address = Address.objects.create(user=request.user) else: message = _('Only less than %(address_limit)s addresses will be allowed.') % {'address_limit':limit} result = False result_dict['success'] = result result_dict['message'] = message return JsonResponse(result_dict) else: try: address = Address.objects.get(user=request.user,id=address_id) except Exception as err: logger.debug('Can not find address which address_id is %s and belongs to %s .' %(address_id,request.user.email)) return JsonResponse(result_dict) form = address_form(request.POST,instance=address) if form.is_valid(): address.useage = useage address.save() result = True message=_('Address successfully saved.') else: logger.error('address parameter error.' + str(request.POST)) elif method == 'del': logger.debug('TDDO: Delete address') else: pass else: #ctx['form'] = address_form() if method == 'modify': try: address = Address.objects.get(id=id,user=request.user) ctx['address'] = address ctx['title'] = 'Modify Address' logger.debug('first_name:' + address.first_name) except Exception as err: logger.error("Can not find the address which id is %s" % id) raise Http404 elif method == 'add': ctx['title'] = 'Add New Address' elif method == 'delete': address = Address.objects.get(id=id,user=request.user) address.delete() return redirect('/user/address/show/') elif method == 'default': address_list = Address.objects.filter(user=request.user) for address in address_list: logger.debug('id:%s' % (id)) logger.debug('address_id:%s' % (address.id)) if address.id == int(id): address.is_default = True address.save() else: address.is_default = False address.save() return redirect('/user/address/show/') else: raise Http404 return render(request,System_Config.get_template_name() + '/address_detail.html',ctx) result_dict['success'] = result result_dict['message'] = message ret_add = {} ret_add['useage'] = address.useage ret_add['id'] = address.id result_dict['address'] = ret_add return JsonResponse(result_dict)
def view_index(request): ctx = {} ctx['system_para'] = get_system_parameters() ctx['menu_products'] = get_menu_products() ctx['page_name'] = 'Home' return render(request,System_Config.get_template_name() + '/index.html',ctx)
def view_blog_list(request, category_id=None, tdk=None): ctx = {} ctx['system_para'] = get_system_parameters() ctx['menu_products'] = get_menu_products() ctx['page_name'] = 'Blog' def get_all_top_menu(): top_menu_list = Menu.objects.filter(parent=None) return top_menu_list top_menu_list = get_all_top_menu() ctx['menu_list'] = top_menu_list if tdk: customize_tdk(ctx, tdk) try: blog_list_page_size_item = System_Config.objects.get(name='blog_list_page_size') blog_list_page_size = blog_list_page_size_item.val logger.debug('blog_list_page_size is %s .' % blog_list_page_size) except Exception as err: logger.debug('blog_list_page_size is not defined,use the default value 12. \Error Message:%s' % err) blog_list_page_size = 12 if request.method == 'GET': template = 'product_list.html' if 'sort_by' in request.GET: if 'direction' in request.GET: if 'desc' == request.GET['direction']: article_list = Article.objects.filter(category=Article.ARTICLE_CATEGORY_BLOG).order_by( request.GET['sort_by']).reverse() else: article_list = Article.objects.filter(category=Article.ARTICLE_CATEGORY_BLOG).order_by( request.GET['sort_by']) else: article_list = Article.objects.filter(category=Article.ARTICLE_CATEGORY_BLOG).order_by( request.GET['sort_by']) else: article_list = Article.objects.filter(category=Article.ARTICLE_CATEGORY_BLOG).order_by('-sort_order') # 按分类筛选 logger.debug('category_id : %s ' % category_id) if category_id: # 查找该分类是否设置了自定义的分类模板 try: category = ArticleBusiCategory.objects.get(id=category_id) ctx['page_key_words'] = category.keywords ctx['page_description'] = category.short_desc if category.page_title: ctx['page_name'] = category.page_title else: ctx['page_name'] = category.name if category.category_template: template = '/custmize/article_category/' + category.category_template article_list = article_list.filter(busi_category=category) except Exception as err: logger.error('Can not find category which id is %s. Error message is %s ' % (category_id, err)) if 'page_size' in request.GET: logger.debug('the page_size has been detacted') article_list, page_range, current_page = my_pagination(request=request, queryset=article_list, display_amount=request.GET['page_size']) else: article_list, page_range, current_page = my_pagination(request=request, queryset=article_list, display_amount=blog_list_page_size) ctx['article_list'] = article_list ctx['page_range'] = page_range ctx['current_page'] = current_page logger.info('template : ' + template) return TemplateResponse(request, System_Config.get_template_name() + '/' + template, ctx)