def auto_completion(request): """Get a list of products' names for the auto-completion. :return: a JsonResponse with a list of products' name, if succed to get products an HttpResponseBadRequest if the form is not valid an HttpResponse with a redirection to home if acces with another method than POST :rtype: JsonResponse """ if request.method == "POST": form = ProductSearchForm(request.POST) if form.is_valid(): # Get a list of products and create a list of names products = Product.objects.get_products_by_name( form["name"].value()) products_names = [product.name for product in products] products_names = list(set(products_names)) # Create a response as a dict for returning a JsonResponse response = {"products_names": products_names} return JsonResponse(response) else: return HttpResponseBadRequest() # Avoid reach the view by the GET method and redirect to the index return redirect(reverse("homepage:index"))
def get_product(request): """Get a product to substitute based on the user search terms. :return: an HttpResponse with a redirection to substitutes if succeed to get a product an HttpResponse with a template render if fail to get a product an HttpResponse with a redirection to home if acces with another method than POST :rtype: HttpResponse """ if request.method == "POST": product_search_form = ProductSearchForm(request.POST) context = {"product_search_form": product_search_form} if product_search_form.is_valid(): # Get the product by using the name product = Product.objects.get_product_by_name( product_search_form.cleaned_data["name"]) # Redirect to the method find_substitutes if the product exist if product: return redirect( reverse("search:get_substitutes", args=[product.code])) # Else render the substitute page without substitutes else: context["product"] = { "name": product_search_form.cleaned_data["name"] } return render(request, "search/substitutes.html", context=context) # Avoid reach the view by the GET method and redirect to the index return redirect(reverse("homepage:index"))
def custom_login_view(request): product_search_form = ProductSearchForm() context = {"product_search_form": product_search_form} # Get the next view url redirect_to = request.POST.get("next", request.GET.get("next", "homepage:index")) if redirect_to: context["next"] = redirect_to if request.method == "POST": login_form = UserLoginForm(request.POST) email = request.POST["username"] password = request.POST["password"] user = authenticate(request, email=email, password=password) if user is not None: login(request, user) success_message = f"Bonjour {user.first_name} !" messages.success(request, success_message) return redirect(redirect_to) else: fail_message = "Vos identifiants sont incorrects." messages.error(request, fail_message) return redirect(reverse("users:login")) else: login_form = UserLoginForm() context["login_form"] = login_form return render(request, "users/login.html", context=context)
def get_substitutes(request, product_code, page=""): """Get a list of substitutes for a product. :return: an HttpResponse with a template render for displaying the subsitutes :rtype: HttpResponse """ product_search_form = ProductSearchForm() context = {"product_search_form": product_search_form} product = Product.objects.get_product_by_code(product_code) if product: context["product"] = product substitutes = Product.objects.find_substitutes(product.code) if substitutes: # Paginate the subsitutes result pagination = Paginator(substitutes, 6, orphans=3) try: context["substitutes"] = pagination.page(page) except PageNotAnInteger: context["substitutes"] = pagination.page(1) except EmptyPage: context["substitutes"] = pagination.page(pagination.num_pages) return render(request, "search/substitutes.html", context=context)
def registration(request): """Register a user.""" product_search_form = ProductSearchForm() context = {"product_search_form": product_search_form} redirect_to = request.POST.get("next", request.GET.get("next", "homepage:index")) if redirect_to: context["next"] = redirect_to if request.method == "POST": form = UserRegistrationForm(request.POST) if form.is_valid(): email = form.cleaned_data["email"] password = form.cleaned_data["password1"] first_name = form.cleaned_data["first_name"] last_name = form.cleaned_data["last_name"] user = User.objects.create_user( email=email, first_name=first_name, password=password, last_name=last_name, ) user.save() success_message = f"Bienvenue parmis nous {first_name} !" messages.success(request, success_message) return redirect(redirect_to) else: form = UserRegistrationForm() context["form"] = form return render(request, "users/registration.html", context=context)
def search(request, category_slug): if request.method == 'POST': form = ProductSearchForm(request.POST) if form.is_valid(): order_type = form.cleaned_data['order_type'] pickup = request.POST.get('pickup') drop = request.POST.get('drop') request.session['order_type'] = order_type request.session['pickup'] = pickup request.session['drop'] = drop return redirect('.' + '/product') else: messages.error(request, 'Please select correct values.') return render(request, 'search_page.html', {'product_search_form': form}) else: product_search_form = ProductSearchForm() return render(request, 'search_page.html', {'product_search_form': product_search_form})
def account(request): """User account details.""" product_search_form = ProductSearchForm() context = {"product_search_form": product_search_form} redirect_to = request.POST.get("next", request.GET.get("next", "homepage:index")) if redirect_to: context["next"] = redirect_to return render(request, "users/account.html", context=context)
def product_list(request): """ 商品一覧(スタッフ) :param request: :return: """ search_form = ProductSearchForm(request.GET) # Queryset初期値 qs = Product.objects.none() # 現在のページを取得。pageパラメータがなければ、1(最初のページを指定) current_page = request.GET.get('page', 1) # 検索 if search_form.is_valid(): cleaned_data = search_form.cleaned_data qs = Product.objects.filter(is_deleted=False).order_by('-updated_at') # 商品名 if cleaned_data['name']: qs = qs.filter(name__icontains=cleaned_data['name']) # 価格(から) if cleaned_data['price_from']: qs = qs.filter(price__gte=cleaned_data['price_from']) # 価格(まで) if cleaned_data['price_to']: qs = qs.filter(price__lte=cleaned_data['price_to']) # カテゴリー if cleaned_data['category']: qs = qs.filter(category=cleaned_data['category']) # 公開ステータス if cleaned_data['is_published']: qs = qs.filter(is_published=cleaned_data['is_published']) page_obj = paginate_query(request, qs) return render(request, 'product/product_list.html', context={ 'current_page': current_page, 'page_obj': page_obj, 'search_form': search_form, })
def custom_server_error(request): """Custom page for 500 errors""" product_search_form = ProductSearchForm() context = { "product_search_form": product_search_form, } template = loader.get_template("500.html") body = template.render(context, request) return HttpResponseServerError(body)
def custom_permission_denied(request, exception): """Custom page for 403 errors""" product_search_form = ProductSearchForm() context = { "product_search_form": product_search_form, } template = loader.get_template("403.html") body = template.render(context, request) return HttpResponseForbidden(body)
def custom_bad_request(request, exception): """Custom page for 400 errors""" product_search_form = ProductSearchForm() context = { "product_search_form": product_search_form, } template = loader.get_template("400.html") body = template.render(context, request) return HttpResponseBadRequest(body)
def top(request): products = Product.objects.order_by('name') form = ProductSearchForm(request.GET) products = form.filter_products(products) params = request.GET.copy() if 'page' in params: page = params['page'] del params['page'] else: page = 1 search_params = params.urlencode() paginator = Paginator(products, 5) page = request.GET.get('page', 1) try: products = paginator.page(page) except (EmptyPage, PageNotAnInteger): products = paginator.page(1) return TemplateResponse(request, 'top/toppage.html', { 'products': products, 'form': form, 'search_params': search_params })
def custom_page_not_found(request, exception): """Custom page for 404 errors""" exception_repr = exception.__class__.__name__ try: message = exception.args[0] except (AttributeError, IndexError): pass else: if isinstance(message, str): exception_repr = message product_search_form = ProductSearchForm() context = { "request_path": quote(request.path), "exception": exception_repr, "product_search_form": product_search_form, } template = loader.get_template("404.html") body = template.render(context, request) return HttpResponseNotFound(body, content_type=None)
def test_search_form_with_one_character_is_invalid(self): data = {"name": "n"} form = ProductSearchForm(data=data) self.assertFalse(form.is_valid())
def test_search_form_with_two_characters_is_valid(self): data = {"name": "nu"} form = ProductSearchForm(data=data) self.assertTrue(form.is_valid())
def disclaimer(request): """Display the disclaimer.""" product_search_form = ProductSearchForm() context = {"product_search_form": product_search_form} return render(request, "homepage/disclaimer.html", context=context)
def test_search_form_with_more_than_hundred_characters_is_invalid(self): data = {"name": 101 * "n"} form = ProductSearchForm(data=data) self.assertFalse(form.is_valid())
def index(request): """Landing page.""" product_search_form = ProductSearchForm() context = {"product_search_form": product_search_form} return render(request, "homepage/home.html", context=context)