def Search(request):
    if request.method == 'POST':
        form = SearchForm(request.POST)
        if form.is_valid():
            url = form.cleaned_data['booking_url']
            crawler = Booking_crawler(url)
            isfile = crawler.Scrapy_Review()
            s = []
            if isfile:
                hotel_name = crawler.pagename
                review = pd.read_csv('cache/' + hotel_name + '.csv')
                s = review['comm']
            else:
                review, hotel_name = crawler.ToCSV()
                s = review['comm']
            context = {
                's': s,
                'hotel_name': hotel_name,
            }
            return render(request, 'simple_crawl.html', context)
    else:
        form = SearchForm(initial={'booking_url': ''})

    context = {
        'form': form,
    }
    return render(request, 'home.html', context)
Beispiel #2
0
def index(request):
    if request.user.is_authenticated:
        following_course = request.user.following_courses
        following = request.user.following_courses
        ndocs = max(5, len(following))
        docs = Document.objects.filter(
            course__in=following).order_by("-created")[:ndocs]
        context = {
            "search": SearchForm(),
            "recent_docs": docs,
            "faculties": Category.objects.get(level=0).children.all(),
            "following_course": following_course,
        }
        return render(request, "home.html", context)
    else:

        def floor(num, r=1):
            r = 10**r
            return int((num // r) * r) if r != 0 else 0

        if Document.objects.count():
            page_count = Document.objects.all().aggregate(
                Sum("pages"))["pages__sum"]
        else:
            page_count = 0

        context = {
            "debug": settings.DEBUG,
            "documents": floor(Document.objects.count()),
            "pages": floor(page_count, 2),
            "users": floor(User.objects.count()),
        }
        return render(request, "index.html", context)
Beispiel #3
0
def opt_pc(request):
    form = SearchForm(initial={'category': 50})
    pc_count = Product.objects.filter(category_id=50).count()
    vnd_lst = {'dell': 76, 'hp': 14, 'acer': 49, 'lenovo': 46}
    cat_lst = {'cpu': 11, 'mb': 12, 'ram':13, 'graph': 14, 'hdd': 15, 'ssd': 16, 'power': 17, 'case': 18}
    cntv = count_vendor(vnd_lst, 50)
    cntc = count_category(cat_lst)
    components = 0
    for i in cntc:
        components += cntc[i]

    r = Price.objects.filter(type=1, price__gt=0).filter(product__category_id=50).order_by('price')[0:20]
    tab = list()
    for i in r:
        i.price = marzha(i.price)
        i.price = '{0:,}'.format(i.price).replace(',', '\xa0') + '\xa0₸'
        tab.append(i)

    context = {
        'form': form,
        'tab': tab,
        'pc_count': pc_count,
        'cntv': cntv,
        'cntc': cntc,
        'components': components,
    }
    return render(request, 'front/opt_pc.html', context)
Beispiel #4
0
def opt_monoblock(request):
    form = SearchForm(initial={'category': 31})
    all_count = Product.objects.filter(category_id=31).count()
    vnd_lst = {'dell': 76, 'hp': 14, 'acer': 49, 'lenovo': 46, 'apple': 98, 'msi': 71, 'asus': 17, 'dream': 250}
    cat_lst = {'battery': 93, 'vr': 99, 'extcd': 223, 'exthdd': 21, 'sd': 89, 'cartreader': 117, 'webcam': 86,
               'akust': 97, 'keyboard': 25, 'keymouse': 26, 'kovrik': 127, 'mfu': 28, 'mouse': 24, 'naush': 56,
               'akustportable': 74, 'printer': 29, 'software': 54, 'scaner': 80, 'sumkanout': 75, 'flesh': 45}

    cntv = count_vendor(vnd_lst, 31)
    cntc = count_category(cat_lst)
    components = 0

    for i in cntc:
        components += cntc[i]

    nts = Price.objects.filter(type=1, price__gt=0).filter(product__category_id=31).order_by('price')[0:20]
    nouts = list()
    for i in nts:
        i.price = marzha(i.price)
        i.price = '{0:,}'.format(i.price).replace(',', '\xa0') + '\xa0₸'
        nouts.append(i)

    # print(nouts)

    context = {
        'form': form,
        'nouts': nouts,
        'all_count': all_count,
        'cntv': cntv,
        'cntc': cntc,
        'components': components,
    }
    return render(request, 'front/opt_monoblock.html', context)
Beispiel #5
0
class ProductSearchView(BaseProductLisView):
    template_name = 'catalog/product_list.html'
    search = ''
    category = None

    def get_queryset(self):
        qs = super(ProductSearchView, self).get_queryset()
        self.form = SearchForm(self.request.GET)
        if self.form.is_valid():
            self.category = self.form.cleaned_data.get('categories', None)
            if self.category:
                child_ids = []
                for o in self.category.childs.published():
                    child_ids.append(o.id)
                    for c in o.childs.published():
                        child_ids.append(c.id)
                child_ids.append(self.category.id)

                qs = qs.filter(category__in=child_ids)
            self.search = self.form.cleaned_data.get('search', None)
            qs = qs.filter(title__icontains=self.search)
        return qs

    def get_context_data(self, **kwargs):
        ctx = super(ProductSearchView, self).get_context_data(**kwargs)
        ctx['products'] = self.get_queryset()
        ctx['search'] = self.search
        ctx['search_category'] = self.category
        return ctx
Beispiel #6
0
def index(request):
    if request.user.is_authenticated:
        following = request.user.following_courses()
        ndocs = max(5, len(following))
        docs = Document.objects.filter(
            course__in=following).order_by("-created")[:ndocs]
        context = {
            'search':
            SearchForm(),
            'stream':
            user_stream(request.user).exclude(verb="started following")[:10],
            'recent_docs':
            docs,
            'faculties':
            Category.objects.get(level=0).children.all()
        }
        return render(request, "home.html", context)
    else:

        def floor(num, r=1):
            r = 10**r
            return int((num // r) * r)

        page_count = Document.objects.all().aggregate(
            Sum('pages'))['pages__sum']

        context = {
            "login_url": NetidBackend.login_url(""),
            "debug": settings.DEBUG,
            "documents": floor(Document.objects.count()),
            "pages": floor(page_count, 2),
            "users": floor(User.objects.count()),
            "threads": floor(Thread.objects.count()),
        }
        return render(request, "index.html", context)
Beispiel #7
0
    def get_queryset(self):
        qs = super(ProductSearchView, self).get_queryset()
        self.form = SearchForm(self.request.GET)
        if self.form.is_valid():
            self.category = self.form.cleaned_data.get('categories', None)
            if self.category:
                child_ids = []
                for o in self.category.childs.published():
                    child_ids.append(o.id)
                    for c in o.childs.published():
                        child_ids.append(c.id)
                child_ids.append(self.category.id)

                qs = qs.filter(category__in=child_ids)
            self.search = self.form.cleaned_data.get('search', None)
            qs = qs.filter(title__icontains=self.search)
        return qs
Beispiel #8
0
def check_product_and_get_attributes(request):
	if request.method == 'POST':
		form = SearchForm(request.POST)
		if form.is_valid():
			article = form.cleaned_data['article']
			manufacturer_from = form.cleaned_data['manufacturer_from']
			
			resp = check_product(article, manufacturer_from)
			
			if resp['correctly']:
				attributes_array = get_attributes(resp['product'])
				return JsonResponse({'result': attributes_array, 'error': False}, content_type='application/json')
			else:
				MainLog(user=request.user, message=resp['error_system']).save()
				return JsonResponse(resp, content_type='application/json')
			
	return JsonResponse({"success": True}, content_type='application/json')
Beispiel #9
0
def advanced_search(request):
	if request.method == 'POST':
		form = SearchForm(request.POST)
		if form.is_valid():
			article = form.cleaned_data['article']
			manufacturer_from = form.cleaned_data['manufacturer_from']
			manufacturer_to = form.cleaned_data['manufacturer_to']
			try:
				product = Product.objects.get(article=article, manufacturer=manufacturer_from)
			except Product.DoesNotExist:
				MainLog(user=request.user,
				        message='По артикулу: {} и производителю: {} не найдено товара'.format(article,
				                                                                                       manufacturer_from)).save()
				return JsonResponse({'result': [], 'error': "Не найден продукт"}, content_type='application/json')
			except Product.MultipleObjectsReturned:
				MainLog(user=request.user,
				        message='По артикулу: {} и производителю: {} найдено несколько товаров'.format(article,
				                                                                                       manufacturer_from)).save()
				return JsonResponse({'result': [], 'error': "Найдено несколько продуктов, уточните поиск"},
				                    content_type='application/json')
			attributes_array = get_attributes(product)
			advanced_form = AdvancedSearchForm(request.POST, extra=attributes_array.get('attributes'))
			if advanced_form.is_valid():
				advanced_form.cleaned_data['manufacturer_from'] = product.manufacturer
				advanced_form.cleaned_data['manufacturer_to'] = manufacturer_to
				MainLog(user=request.user,
				        message='По артикулу: {} и производителю: {} запрошен расширенный поиск: {}'.format(article,
				                                                                                       manufacturer_from,
				                                                                                        advanced_form.cleaned_data)).save()
				result = SearchProducts(request, advanced_form, product)
				return result_api_processing(result, request, product, default=False)
			else:
				MainLog(user=request.user,
				        message='Произошла ошибка при расширенном поиске по артикулу: {} и производителю: {}'.format(article,
				                                                                                            manufacturer_from)).save()
				return render(request, 'admin/catalog/search.html', {'error': 'Ошибка формы'})
		MainLog(user=request.user,
		        message='Произошла ошибка при расширенном поиске, невалидная форма').save()
		return render(request, 'admin/catalog/search.html', {'error': 'Ошибка формы'})
	MainLog(message='Неверный тип запроса расширенного поиска').save()
	return JsonResponse({'result': [], 'error': "Произошла ошибка при выполнении запроса"},
	                    content_type='application/json')
Beispiel #10
0
def index():
    form = SearchForm(request.form)

    if request.method == 'GET' or not form.validate_on_submit():
        return render_template('index.html', form=form)

    city_name = form.city.data
    room_count = form.room_count.data

    query = db.session.query(Flat).join(Flat.buildings).join(Building.group).join(BuildingGroup.city)
    query = query.filter(or_(City.name.contains(city_name.capitalize()), City.name.contains(city_name.lower())))
    query = query.filter(Flat.room_count >= room_count)
    subquery = query.subquery()

    # Select minimal price in group of buildings
    grouped_subquery = db.session.query(
        Flat.id,
        func.min(Flat.price)
    ).join(Flat.buildings).join(subquery, Flat.id == subquery.c.id).group_by(Building.id).subquery()

    query = query.join(grouped_subquery, Flat.id == grouped_subquery.c.id)
    flats = query.order_by(Flat.full_price)

    return render_template('index.html', form=form, flats=flats)
Beispiel #11
0
def search_from_form(request):
	# print(vars(request), request.method, request.method.POST)
	if request.method == 'POST':
		form = SearchForm(request.POST)
		print( 'POST')
		if form.is_valid():
			# article = form.cleaned_data['article']
			# manufacturer_from = form.cleaned_data['manufacturer_from']
			
			# resp = check_product(article, manufacturer_from)
			
			# if resp.get('correctly'):
			
			result = SearchProducts(request, form)
			return result_api_processing(result, request, default=True)
			# else:
				# MainLog(user=request.user, message=resp['error_system']
				#         ).save()
				# return JsonResponse(resp, content_type='application/json')
			
		return JsonResponse({'error':'not valid form'}, content_type='application/json')
		# return render(request, 'admin/catalog/search.html', {'error': 'Ошибка формы'})
	
	return JsonResponse({'result': [], 'error': "Произошла ошибка при выполнении запроса"}, content_type='application/json')
Beispiel #12
0
def search_course(request):
    if request.method == 'POST':
        form = SearchForm(request.POST)

        if form.is_valid():
            name = form.cleaned_data['name']
            results = search.logic.search_course(name)

        else:
            form = SearchForm()
            results = []
    else:
        form = SearchForm()
        results = []

    if len(results) == 1:
        # We have only one result, redirect immediately to the course
        course = results[0]
        return HttpResponseRedirect(reverse('course_show', args=[course.slug]))

    return render(request, 'catalog/course_search.html', {
        'form': form,
        'results': results,
    })
Beispiel #13
0
 def get_context_data(self, **kwargs):
     # Call the base implementation first to get the context
     context = super(BookSearchView, self).get_context_data(**kwargs)
     # Create any data and add it to the context
     context['form'] = SearchForm()
     return context