def register_view(request, template_name="registration/register.html"): """Регистрация нового пользователя""" device = change_template_for_device(request, template_name)['device'] page_title = _(u'User Registration') request.breadcrumbs(page_title, request.path_info) if request.method == 'POST': postdata = request.POST.copy() form = MyRegistrationForm(postdata) if form.is_valid(): form.save() un = postdata.get('username', '') # name="password1" т.к. два поля с подтверждением pw = postdata.get('password1', '') new_user = authenticate(username=un, password=pw) if new_user and new_user.is_active: # отправляем e-mail о регистрации нового пользователя subject = u'waymy.ru регистрация %s' % new_user.username message = u' Зарегистрирован новый пользователь %s' % ( new_user.username) send_mail(subject, message, '*****@*****.**', [ADMIN_EMAIL], fail_silently=False) login(request, new_user) # Редирект на url с именем my_account url = urlresolvers.reverse('my_account') return HttpResponseRedirect(url) else: form = MyRegistrationForm() return render_to_response(template_name, locals(), context_instance=RequestContext(request))
def review_form_view(request, template_name="pages/review.html"): device = change_template_for_device(request, template_name)['device'] try: meta_object = MetaInPages.objects.get(link=request.path) except: pass request.breadcrumbs(u'Отзывы', request.path_info) try: current_userProfile = UserProfile.objects.get(user=request.user) reviews = Review.objects.all() if request.method == 'POST': postdata = request.POST.copy() form = ReviewForm(postdata) if form.is_valid(): new_review = Review() new_review.review = postdata.get('review', '') new_review.user = request.user new_review.save() url = urlresolvers.reverse('my_account') return HttpResponseRedirect(url) else: user_profile = request.user form = ReviewForm(instance=user_profile) except: text = u'Вы не заполнили свой профиль' reviews = Review.objects.all() return render_to_response(template_name, locals(), context_instance=RequestContext(request))
def pageView(request, slug, template_name="pages/page.html", *args): device = change_template_for_device(request, template_name)['device'] page = Page.objects.get(slug=slug) try: meta_object = MetaInPages.objects.get(link=request.path) except: pass request.breadcrumbs('%s' % page.name, request.path_info) if request.user.is_superuser: try: if request.method == 'POST': postdata = request.POST.copy() form = PageForm(postdata) if form.is_valid(): page.name = postdata.get('name', '') page.slug = postdata.get('slug', '') page.text = postdata.get('text', '') page.is_main = False page.save() # new_review = form.save(commit=False) form = PageForm(instance=page) url = urlresolvers.reverse(request.path_info) return HttpResponseRedirect(url) else: # user_profile = request.user if request.user.is_superuser: form = PageForm(instance=page) except: text = u'Вы не имеете право' return render_to_response(template_name, locals(), context_instance=RequestContext(request))
def results_view(request, template_name="search/results.html"): """Представление для результатов поиска""" device = change_template_for_device(request, template_name)['device'] # Получаем номер текущей страницы. Устанавливаем 1 если не найдена try: page = int(request.GET.get('page', 1)) except ValueError: page = 1 # получаем поисковую фразу query = request.GET.get('query', '') # print query # возвращаем найденные продукты matching = search.products(query) # Создаем объект класса Paginator # paginator = Paginator(matching, settings.PRODUCTS_PER_PAGE) # try: # results = paginator.page(page).object_list # except (InvalidPage, EmptyPage): # results = paginator.page(1).object_list results = matching for p in results: try: p.image_url = ProductImage.objects.get(product=p, default=True).url except Exception: p.image_url = "/media/products/images/none.png" # Сохраняем поисковую фразу # search.store(request, query) page_title = 'Search Results for: ' + query return render_to_response(template_name, locals(), context_instance=RequestContext(request))
def review_form_view(request, template_name="pages/review.html"): device = change_template_for_device(request, template_name)['device'] try: meta_object = MetaInPages.objects.get(link=request.path) except: pass request.breadcrumbs(u'Отзывы', request.path_info) try: current_userProfile = UserProfile.objects.get(user=request.user) reviews = Review.objects.all() if request.method == 'POST': postdata = request.POST.copy() form = ReviewForm(postdata) if form.is_valid(): new_review = Review() new_review.review = postdata.get('review', '') new_review.user = request.user new_review.save() url = urlresolvers.reverse('my_account') return HttpResponseRedirect(url) else: user_profile = request.user form = ReviewForm(instance=user_profile) except: text = u'Вы не заполнили свой профиль' reviews = Review.objects.all() return render_to_response(template_name, locals(),context_instance=RequestContext(request))
def register_view(request, template_name="registration/register.html"): """Регистрация нового пользователя""" device = change_template_for_device(request, template_name)['device'] page_title = _(u'User Registration') request.breadcrumbs(page_title, request.path_info) if request.method == 'POST': postdata = request.POST.copy() form = MyRegistrationForm(postdata) if form.is_valid(): form.save() un = postdata.get('username', '') # name="password1" т.к. два поля с подтверждением pw = postdata.get('password1', '') new_user = authenticate(username=un, password=pw) if new_user and new_user.is_active: # отправляем e-mail о регистрации нового пользователя subject = u'waymy.ru регистрация %s' % new_user.username message = u' Зарегистрирован новый пользователь %s' % (new_user.username) send_mail(subject, message, '*****@*****.**', [ADMIN_EMAIL], fail_silently=False) login(request, new_user) # Редирект на url с именем my_account url = urlresolvers.reverse('my_account') return HttpResponseRedirect(url) else: form = MyRegistrationForm() return render_to_response(template_name, locals(), context_instance=RequestContext(request))
def pageView(request, slug, template_name="pages/page.html", *args): device = change_template_for_device(request, template_name)['device'] page = Page.objects.get(slug=slug) try: meta_object = MetaInPages.objects.get(link=request.path) except: pass request.breadcrumbs('%s' % page.name, request.path_info) if request.user.is_superuser: try: if request.method == 'POST': postdata = request.POST.copy() form = PageForm(postdata) if form.is_valid(): page.name = postdata.get('name', '') page.slug = postdata.get('slug', '') page.text = postdata.get('text', '') page.is_main = False page.save() # new_review = form.save(commit=False) form = PageForm(instance=page) url = urlresolvers.reverse(request.path_info) return HttpResponseRedirect(url) else: # user_profile = request.user if request.user.is_superuser: form = PageForm(instance=page) except: text = u'Вы не имеете право' return render_to_response(template_name, locals(),context_instance=RequestContext(request))
def news_view(request, news_slug, template_name="news.html"): """Представление для конкретной новости""" device = change_template_for_device(request, template_name)['device'] news = get_object_or_404(News, slug=news_slug) return render_to_response(template_name, { 'news': news, }, context_instance=RequestContext(request))
def articlesView(request, template_name="pages/articles.html"): # :TODO не плохое решение метотэгов на основе текущего урла device = change_template_for_device(request, template_name)['device'] try: meta_object = MetaInPages.objects.get(link=request.path) except: pass articles = Article.objects.all() return render_to_response(template_name, locals(),context_instance=RequestContext(request))
def articlesView(request, template_name="pages/articles.html"): # :TODO не плохое решение метотэгов на основе текущего урла device = change_template_for_device(request, template_name)['device'] try: meta_object = MetaInPages.objects.get(link=request.path) except: pass articles = Article.objects.all() request.breadcrumbs([("Сатьи", "")]) return render_to_response(template_name, locals(), context_instance=RequestContext(request))
def my_account_view(request, template_name="registration/my_account.html"): """Страница аккаунта пользователя""" device = change_template_for_device(request, template_name)['device'] page_title = _(u'My Account') request.breadcrumbs(page_title, request.path_info) if request.user.is_superuser: orders = Order.objects.all() else: orders = Order.objects.filter(user=request.user) name = request.user.username return render_to_response(template_name, locals(), context_instance=RequestContext(request))
def my_account_view(request, template_name="registration/my_account.html"): """Страница аккаунта пользователя""" device = change_template_for_device(request, template_name)['device'] page_title = _(u'My Account') request.breadcrumbs(page_title, request.path_info) if request.user.is_superuser: orders = Order.objects.all() else: orders = Order.objects.filter(user=request.user) name = request.user.username return render_to_response(template_name, locals(), context_instance=RequestContext(request))
def cart_view(request, template_name="cart/cart.html"): """Представление для отображения корзины""" device = change_template_for_device(request, template_name)['device'] template_name = change_template_for_device(request, template_name)['template_name'] page_title = _(u'Shopping cart') if request.method == 'POST': postdata = request.POST.copy() if postdata.has_key('remove'): cart.remove_from_cart(request) if postdata.has_key('update'): cart.update_cart(request) """отправляем request на пересчет корзины по купону""" if postdata.has_key('update_cupon'): cart.update_cupon_cart(request) if postdata.has_key('checkout'): checkout_url = checkout.get_checkout_url(request) return HttpResponseRedirect(checkout_url) deliveryForm = DeliveryForm() request.breadcrumbs(u'Корзина', request.path_info) # Получаем список всех товаров в корзине из cookies #cart_item_count = cart.cart_item_count(request) cart_items = cart.get_cart_items(request) cart_subtotal = cart.cart_subtotal(request) # cart_gift = cart.cart_gift_add(request) # доставка # delivery = cart.get_delivery(request) # delivery.save() # cart_total = cart.cart_total(request) return render_to_response(template_name, locals(), context_instance=RequestContext(request))
def order_details_view(request, order_id, template_name="registration/order_details.html"): """Информация о сделанном заказе""" device = change_template_for_device(request, template_name)['device'] if request.user.is_superuser: order = get_object_or_404(Order, id=order_id) else: order = get_object_or_404(Order, id=order_id, user=request.user) page_title = _(u'Order details for order #') + order_id request.breadcrumbs(page_title, request.path_info) order_items = OrderItem.objects.filter(order=order) total_sum_parse = "%s" % order.total total_sum_parse = total_sum_parse.split(".") return render_to_response(template_name, locals(), context_instance=RequestContext(request))
def order_details_view(request, order_id, template_name="registration/order_details.html"): """Информация о сделанном заказе""" device = change_template_for_device(request, template_name)['device'] if request.user.is_superuser: order = get_object_or_404(Order, id=order_id) else: order = get_object_or_404(Order, id=order_id, user=request.user) page_title = _(u'Order details for order #') + order_id request.breadcrumbs(page_title, request.path_info) order_items = OrderItem.objects.filter(order=order) total_sum_parse = "%s" % order.total total_sum_parse = total_sum_parse.split(".") return render_to_response(template_name, locals(), context_instance=RequestContext(request))
def order_info_view(request, template_name="registration/order_info.html"): """Представление данных профиля""" device = change_template_for_device(request, template_name)['device'] if request.method == 'POST': postdata = request.POST.copy() form = UserProfileForm(postdata) if form.is_valid(): profile.set(request) url = urlresolvers.reverse('my_account') return HttpResponseRedirect(url) else: user_profile = profile.retrieve(request) form = UserProfileForm(instance=user_profile) page_title = _(u'Edit Order Information') request.breadcrumbs(page_title, request.path_info) return render_to_response(template_name, locals(), context_instance=RequestContext(request))
def order_info_view(request, template_name="registration/order_info.html"): """Представление данных профиля""" device = change_template_for_device(request, template_name)['device'] if request.method == 'POST': postdata = request.POST.copy() form = UserProfileForm(postdata) if form.is_valid(): profile.set(request) url = urlresolvers.reverse('my_account') return HttpResponseRedirect(url) else: user_profile = profile.retrieve(request) form = UserProfileForm(instance=user_profile) page_title = _(u'Edit Order Information') request.breadcrumbs(page_title, request.path_info) return render_to_response(template_name, locals(), context_instance=RequestContext(request))
def news_all_view(request, template_name="news_all.html"): """Представление для конкретной новости""" device = change_template_for_device(request, template_name)['device'] news = News.objects.all() return render_to_response(template_name, {'news': news}, context_instance=RequestContext(request))
def news_view(request, news_slug, template_name="news.html"): """Представление для конкретной новости""" device = change_template_for_device(request, template_name)['device'] news = get_object_or_404(News, slug=news_slug) return render_to_response(template_name, {'news': news,}, context_instance=RequestContext(request))
def news_all_view(request, template_name="news_all.html"): """Представление для конкретной новости""" device = change_template_for_device(request, template_name)['device'] news = News.objects.all() return render_to_response(template_name, {'news': news}, context_instance=RequestContext(request))
def receipt_view(request, template_name='checkout/receipt.html'): """Представление отображающее сделанный заказ""" request.breadcrumbs(u'Подтверждение данных', request.path_info) device = change_template_for_device(request, template_name)['device'] order_id = request.session.get('order_id', '') if order_id: # если в cookies есть номер заказа, выводим его содержимое order = Order.objects.get(id=order_id) order_items = OrderItem.objects.filter(order=order) order_items = OrderItem.objects.filter(order=order) items = '' for item in order_items: items = items + '%s \n' % item.name subject = u'waymy.ru заказ создан оплата не произошла ' message = u'Имя: %s \n телефон: %s \n почта: %s \n \ id заказа: %s \n Товары: %s' % (order.shipping_name, order.phone, order.email, order.id, items) send_mail(subject, message, '*****@*****.**', [ADMIN_EMAIL], fail_silently=False) delivery = order.delivery total = order.total if request.user.username == 'admin': total = 1 if order.payment_method == 2: form = RobokassaForm(initial={ 'OutSum': total, 'InvId': order.id, }) else: """на данный момент следующий код не работает потому что отключена возможность выбора способа оплаты""" """отправка писем""" items = '' for item in order_items: items = items + '%s \n' % item.name if order.payment_method == 1: payment_method = u'Оплатить квитанцию' else: payment_method = u'Оплата онлайн' subject = u'waymy.ru заявка от %s' % order.shipping_name message = u'Номер транзакции №: %s \n Имя: %s \n телефон: %s \n почта: %s \n id заказа: %s \n Товары: %s \n %s \n Тип доставки: %s \n Вес доставки: %s \n Адрес: %s \n Стоимость доставки: %s \n Общая стоимость: %s' % ( order.transaction_id, order.shipping_name, order.phone, order.email, order.id, items, payment_method, delivery.delivery_type, delivery.weight, order.shipping_address_1, delivery.delivery_price, order.total) send_mail(subject, message, '*****@*****.**', [ADMIN_EMAIL], fail_silently=False) context_dict = { 'transaction': order.transaction_id, 'id': order.id, 'items': items, 'total': order.total, 'payment_method': payment_method, } message = render_to_string('checkout/email.html', context_dict) from_email = '*****@*****.**' to = '%s' % order.email msg = EmailMultiAlternatives(subject, message, from_email, [to]) msg.content_subtype = "html" msg.send() cupon_done = Cupon.objects.get(id=order.cupon.id) cupon_done.percent = '0' cupon_done.save() price_order = '%s' % order.total price_order = price_order.split(".") template_name = 'checkout/receipt_print.html' if request.POST == 'POST': del request.session['order_id'] else: # иначе перенаправляем пользователя на страницу корзины cart_url = urlresolvers.reverse('show_cart') return HttpResponseRedirect(cart_url) return render_to_response(template_name, locals(), context_instance=RequestContext(request))
def contact(request, template_name='checkout/checkout.html'): device = change_template_for_device(request, template_name)['device'] request.breadcrumbs(u'Данные получателя', request.path_info) if cart.is_empty(request): cart_url = urlresolvers.reverse('show_cart') return HttpResponseRedirect(cart_url) if request.method == 'POST': form = ContactForm(request.POST) phone = request.POST['phone'] if form.is_valid(): form.clean_phone() """создание пользователя при оформлении заказа если не зарегистрирован""" #1 создать user #2 отправить письмо #3 создать User_profile if not request.user.is_authenticated(): name, nu = request.POST['email'].split('@')[:2] try: login_exist = User.objects.filter(username__icontains=name) if login_exist: name = '%s%s' % (name, login_exist.count()) except Exception: name = name new_user = User(username=name, email=request.POST['email']) password = User.objects.make_random_password() new_user.set_password(password) new_user.save() context_dict = { 'name': request.POST['shipping_name'], 'username': new_user.username, 'password': password, } subject = u'Регистрация на сайте www.waymy.ru' message = render_to_string('checkout/reg_email.html', context_dict) from_email = '*****@*****.**' to = new_user.email msg = EmailMultiAlternatives(subject, message, from_email, [to]) msg.content_subtype = "html" msg.send() user = authenticate(username=name, password=password) if user is not None: if user.is_active: login(request, user) profile.set(request) """процесс создания заказа на основе того что было в корзине и на основе введенных данных""" response = checkout.process(request) order = response.get('order', 0) order_id = order.id if order_id: request.session['order_id'] = order_id receipt_url = urlresolvers.reverse('checkout_receipt') return HttpResponseRedirect(receipt_url) else: form = ContactForm(request.POST) return render(request, 'checkout/checkout.html', { 'form': form, 'error': form.errors, }) else: #заполняем форму получателя если пользователь авторизирован if request.user.is_authenticated(): user_profile = profile.retrieve(request) form = ContactForm(instance=user_profile) else: form = ContactForm() return render_to_response(template_name, locals(), context_instance=RequestContext(request))
def receipt_view(request, template_name='checkout/receipt.html'): """Представление отображающее сделанный заказ""" request.breadcrumbs(u'Подтверждение данных', request.path_info) device = change_template_for_device(request, template_name)['device'] order_id = request.session.get('order_id', '') if order_id: # если в cookies есть номер заказа, выводим его содержимое order = Order.objects.get(id=order_id) order_items = OrderItem.objects.filter(order=order) delivery = order.delivery total = order.total if request.user.username == 'admin': total = 1 if order.payment_method == 2: form = RobokassaForm(initial={ 'OutSum': total, 'InvId': order.id, }) else: """на данный момент следующий код не работает потому что отключена возможность выбора способа оплаты""" """отправка писем""" items = '' for item in order_items: items = items + '%s \n' % item.name if order.payment_method == 1: payment_method = u'Оплатить квитанцию' else: payment_method = u'Оплата онлайн' subject = u'waymy.ru заявка от %s' % order.shipping_name message = u'Номер транзакции №: %s \n Имя: %s \n телефон: %s \n почта: %s \n id заказа: %s \n Товары: %s \n %s \n Тип доставки: %s \n Вес доставки: %s \n Адрес: %s \n Стоимость доставки: %s \n Общая стоимость: %s' % (order.transaction_id, order.shipping_name, order.phone, order.email, order.id, items, payment_method, delivery.delivery_type, delivery.weight, order.shipping_address_1, delivery.delivery_price, order.total) send_mail(subject, message, '*****@*****.**', [ADMIN_EMAIL], fail_silently=False) context_dict = { 'transaction': order.transaction_id, 'id': order.id, 'items': items, 'total': order.total, 'payment_method': payment_method, } message = render_to_string('checkout/email.html', context_dict) from_email = '*****@*****.**' to = '%s' % order.email msg = EmailMultiAlternatives(subject, message, from_email, [to]) msg.content_subtype = "html" msg.send() cupon_done = Cupon.objects.get(id=order.cupon.id) cupon_done.percent = '0' cupon_done.save() price_order = '%s' % order.total price_order = price_order.split(".") template_name = 'checkout/receipt_print.html' if request.POST == 'POST': del request.session['order_id'] else: # иначе перенаправляем пользователя на страницу корзины cart_url = urlresolvers.reverse('show_cart') return HttpResponseRedirect(cart_url) return render_to_response(template_name, locals(), context_instance=RequestContext(request))
def contact(request, template_name='checkout/checkout.html'): device = change_template_for_device(request, template_name)['device'] request.breadcrumbs(u'Данные получателя', request.path_info) if cart.is_empty(request): cart_url = urlresolvers.reverse('show_cart') return HttpResponseRedirect(cart_url) if request.method == 'POST': form = ContactForm(request.POST) phone = request.POST['phone'] if form.is_valid(): form.clean_phone() """создание пользователя при оформлении заказа если не зарегистрирован""" #1 создать user #2 отправить письмо #3 создать User_profile if not request.user.is_authenticated(): name , nu = request.POST['email'].split('@')[:2] try: login_exist = User.objects.filter(username__icontains=name) if login_exist: name = '%s%s' % (name, login_exist.count()) except Exception: name = name new_user = User(username=name, email=request.POST['email']) password = User.objects.make_random_password() new_user.set_password(password) new_user.save() context_dict = { 'name': request.POST['shipping_name'], 'username': new_user.username, 'password': password, } subject = u'Регистрация на сайте www.polythai.ru' message = render_to_string('checkout/reg_email.html', context_dict) from_email = '*****@*****.**' to = new_user.email msg = EmailMultiAlternatives(subject, message, from_email, [to]) msg.content_subtype = "html" msg.send() user = authenticate(username=name, password=password) if user is not None: if user.is_active: login(request, user) profile.set(request) """процесс создания заказа на основе того что было в корзине и на основе введенных данных""" response = checkout.process(request) order = response.get('order', 0) order_id = order.id if order_id: request.session['order_id'] = order_id receipt_url = urlresolvers.reverse('checkout_receipt') return HttpResponseRedirect(receipt_url) else: form = ContactForm(request.POST) return render(request, 'checkout/checkout.html', { 'form': form, 'error': form.errors, }) else: #заполняем форму получателя если пользователь авторизирован if request.user.is_authenticated(): user_profile = profile.retrieve(request) form = ContactForm(instance=user_profile) else: form = ContactForm() return render_to_response(template_name, locals(), context_instance=RequestContext(request))