예제 #1
0
def search(request):
    context = {}
    if request.user.is_authenticated():
        f_user = user_to_fingr(request.user)
        context['authenticated'] = True
        # user is already searching
        if request.POST:
            form = SearchForm(request.POST)
            # display found users
            if form.is_valid():
                # all users
                unfiltered = (FingrUser.objects.filter(username__contains=form.cleaned_data['search']) | FingrUser.objects.filter(first_name__contains=form.cleaned_data['search']) | FingrUser.objects.filter(last_name__contains=form.cleaned_data['search']))
                # set(chain(...)) joins querysets and uniques them
                # http://stackoverflow.com/questions/431628/how-to-combine-2-or-more-querysets-in-a-django-view
                # users without extreme privacy
                visible = unfiltered.exclude(visibility="None")
                friends = {}
                for u in visible:
                    if (u.visibility=="Friends"):
                        friends = set(chain(friends, visible.filter(friends=f_user)))
                all = unfiltered.filter(visibility="All")
                context['userlist'] = set(chain(all, friends))
                return render(request, 'search.html', context)
            else:
                return render(request, 'search.html', context)
        else:
            #context['userlist'] = FingrUser.objects.all()
            return render(request, 'search.html', context)
    return redirect('main.views.index')
예제 #2
0
파일: views.py 프로젝트: vibhcool/MedLib
def search(request):
    if request.method == 'POST':
        topic = SearchForm(request.POST)
        if topic.is_valid():

            #t=Topic.objects.get(topic_text=topic.cleaned_data.get('topic_text'))
            top_li = Topic.objects.all()
            li = []
            for t in top_li:
                if re.search(topic.cleaned_data.get('topic_text'),
                             t.topic_text, re.IGNORECASE):
                    li.append(t)
            if request.session.has_key('user_id'):
                uid = request.session['user_id']
                user = Users.objects.get(pk=uid)
                return render(request, 'Temp/searchresults.html', {
                    'user_id': user,
                    "list": li
                })
            else:
                return render(request, 'Temp/searchresultL.html', {"list": li})
        else:
            return HttpResponse("Form not valid")
    else:
        return HttpResponse("not POST")
예제 #3
0
def MyMention(request):
    sections = Section.objects.all()
    post_num = Post.objects.count()
    user_num = User.objects.filter(is_active=True).count()
    user_extend = None

    if request.GET.has_key('search'):
        form = SearchForm(request.GET)
    else:
        return render(
            request,
            'main/my_mention.html',
            {
                'sections': sections,
                'post_num': post_num,
                'user_num': user_num,
                'err': 'error'
            },
        )

    if form.is_valid():
        user_extend = form.cleaned_data['search']
        query = Comment.objects.exclude(post__status='t').filter( \
            Q(this_comment_quote__comment_by__user__username__iexact=user_extend) | \
            Q(comment_made__icontains=user_extend) ).order_by('-id')
        page = request.GET.get('page', 1)

        paginator = Paginator(query, 20, body=5)

        try:
            allcomment = paginator.page(page)
        except PageNotAnInteger:
            # If page is not an integer, deliver first page.
            allcomment = paginator.page(1)
        except EmptyPage:
            # If page is out of range (e.g. 9999), deliver last page of results.
            allcomment = paginator.page(paginator.num_pages)

        return render(
            request,
            'main/my_mention.html',
            {
                'allcomment': allcomment,
                'sections': sections,
                'post_num': post_num,
                'user_num': user_num,
                'post_owner': user_extend,
            },
        )
    else:
        return render(
            request,
            'main/my_mention.html',
            {
                'sections': sections,
                'post_num': post_num,
                'user_num': user_num,
            },
        )
예제 #4
0
파일: views.py 프로젝트: danimilles/Mobooks
def search(request):
    form = SearchForm()
    mobooks_db = connect_to_db()

    if request.method == 'POST':
        form = SearchForm(request.POST)

        if form.is_valid():
            page = form.cleaned_data.get('page')
            to_show = form.cleaned_data.get('to_show')
            to_skip = (page - 1) * to_show

            order_type = form.cleaned_data.get('order_type')
            reverse = form.cleaned_data.get('reverse')
            asc_or_desc = 1 if reverse is False else -1

            query = {}
            title = form.cleaned_data.get('title')
            match = form.cleaned_data.get('match')
            if title:
                query['title'] = {
                    "$regex": "(.*)" + title + "(.*)"
                } if not match else title

            from_date = form.cleaned_data.get('from_date')
            to_date = form.cleaned_data.get('to_date')
            if from_date or to_date:
                date_compare = {}
                if from_date:
                    date_compare["$gte"] = from_date
                if to_date:
                    date_compare["$lte"] = to_date

                query['release_year'] = date_compare

            genre = form.cleaned_data.get('genre')
            if genre:
                query['genre'] = str(genre)

            publisher = form.cleaned_data.get('publisher')
            if publisher:
                query['publisher'] = str(publisher)

            author = form.cleaned_data.get('author')
            if author:
                query['author'] = str(author)

            books = mobooks_db.main_book.find(query).sort(
                order_type, asc_or_desc).skip(to_skip).limit(to_show)
            return render(request, 'search.html', {
                'form': form,
                'books': books
            })

    return render(
        request, 'search.html', {
            'form': form,
            'books': mobooks_db.main_book.find().sort("title", 1).limit(10)
        })
예제 #5
0
	def get(self,request):
		form = SearchForm(request.GET)

		ctx={
			"form":form
		}
		if form.is_valid():
		 
			name_query=form.cleaned_data.get("name")
			if name_query:

				s=Search(index="daintree").query("match",name=name_query)
			else:
				s=Search(index="daintree")


			min_price=form.cleaned_data.get("min_price")
			max_price=form.cleaned_data.get("max_price")

			if min_price is not None or max_price is not None:
				price_query=dict()
				if min_price is not None:
					price_query["gte"]=min_price
				if max_price is not None:
					price_query["lte"]=max_price
				s=s.query("range",price=price_query)		
			

			s.aggs.bucket("categories","terms",field="category")

			if request.GET.get("category"):
				s=s.query("match",category=request.GET["category"])

			result=s.execute()

			ctx["products"]=result.hits
			category_aggregations=list()
			for bucket in result.aggregations.categories.buckets:
				category_name=bucket.key
				doc_count=bucket.doc_count

				category_url_params=request.GET.copy()
				category_url_params["category"]=category_name

				category_url="{}?{}".format(reverse("home"),category_url_params.urlencode())
				category_aggregations.append({
					"name":category_name,
					"doc_count":doc_count,
					"url":category_url
					})
			ctx["category_aggs"]=category_aggregations
		if "category" in request.GET:
			remove_category_search_params=request.GET.copy()
			del remove_category_search_params["category"]
			remove_category_url="{}?{}".format(reverse("home"),remove_category_search_params.urlencode())
			ctx["remove_category_url"]=remove_category_url
			
		return render(request,"home.html",ctx)
예제 #6
0
def search(request):
    form = SearchForm(request.POST or None)

    if form.is_valid():
        result = form.rest_save(request.user.username, request.session['key_ring'])
        return redirect('search-result', search_id=result['searchId'])

    referer = request.META.get('HTTP_REFERER', 'index')

    return redirect(referer)
예제 #7
0
def buscarPorUsuario(request):
    if request.method == 'POST':
        formulario = SearchForm(request.POST)
        if formulario.is_valid():
            usuarioArtista = UsuarioArtista.objects.filter(
                usuarioId=formulario.cleaned_data['usuarioId'])
            return render_to_response('lista_artistas.html',
                                      {'artistas': usuarioArtista})
    else:
        formulario = SearchForm()
    return render_to_response('search.html', {'formulario': formulario},
                              context_instance=RequestContext(request))
예제 #8
0
파일: views.py 프로젝트: vibhcool/MedLib
def search1(request):
    if request.method == 'POST':
        topic = SearchForm(request.POST, initial={"topic_text": "c"})
        if topic.is_valid():
            sim_str = topic.cleaned_data.get('topic_text')
            checklist = sim_str.split(",")
            #checklist = topic.cleaned_data.get('symptom')

            try:
                checklist.append(request.POST['symptom1'])
            except:
                pass
            try:
                checklist.append(request.POST['symptom2'])
            except:
                pass
            try:
                checklist.append(request.POST['symptom3'])
            except:
                pass
            try:
                checklist.append(request.POST['symptom4'])
            except:
                pass
            try:
                checklist.append(request.POST['symptom5'])
            except:
                pass
            try:
                checklist.append(request.POST['symptom6'])
            except:
                pass
            try:
                checklist.append(request.POST['symptom7'])
            except:
                pass
            #return HttpResponse(checklist)

            li = ob.search_symptoms(checklist)
            l = len(li)
            return render(request, 'Temp/symtoms.html', {"list": li, "len": l})

            #return HttpResponse((' ').join(li))
            #t=Topic.objects.get(topic_text=topic.cleaned_data.get('topic_text'))

        else:
            return HttpResponse("Form not valid")
    else:
        return HttpResponse("not POST")
예제 #9
0
파일: views.py 프로젝트: teamstudios/test
def add_good(request):
    """
    Add good view
    :param request: HttpRequest
    :return: HttpResponse (if error return rendered add_good.html else redirect to good page)
    """
    if request.method == 'POST':
        properties_form = GoodPropetiesForm(request.POST)
        good_form = GoodForm(request.POST)
        image_upload_form = CustomImageUpload(request.POST)
        if good_form.is_valid() and properties_form.is_valid(
        ) and image_upload_form.is_valid():
            # Get tags
            tags_names = good_form.cleaned_data['tags']
            tags = [Tag.objects.get(name=name) for name in tags_names]
            new_good = good_form.save(commit=False)
            new_good.user = request.user
            new_good.save()
            for tag in tags:
                new_good.tags.add(tag)
            new_good_properties = properties_form.save(commit=False)
            new_good_properties.good = new_good
            new_good_properties.save()
            # Get images ids
            images_ids = list(image_upload_form.cleaned_data.values())
            # Clear empty strings from images_ids
            indexes_images = len(images_ids) - 1
            while indexes_images >= 0:
                if not images_ids[indexes_images].isdigit():
                    images_ids.pop(indexes_images)
                indexes_images -= 1
            # Add photos only we have ids
            if len(images_ids) > 0:
                photos = GoodsPhotos.objects.filter(id__in=images_ids)
                photos.update(good=new_good)
            # Post to social networks with links
            site = get_current_site(request)
            post_to_social_network.delay(request.user.pk, new_good.pk,
                                         site.domain)
            return redirect(reverse('goods:good_view', args=[new_good.pk]))
        else:
            messages.error(request, _("Error adding goods"))
    else:
        image_upload_form = CustomImageUpload()
        good_form = GoodForm(initial={
            'deal': AUCTION
        })  # Set initial type to auction because it's first slider
        properties_form = GoodPropetiesForm()
    search_form = SearchForm()
    all_tags = Tag.objects.all()
    return render(
        request, 'add_good.html', {
            'search_form': search_form,
            'good_form': good_form,
            'image_upload_form': image_upload_form,
            'properties_form': properties_form,
            'all_tags': all_tags,
        })
예제 #10
0
def show_results(request):

    if request.method == "POST":
        form = SearchForm(request.POST)
        if form.is_valid():
            text = form.cleaned_data.get('search')
            form.save()
            table_recommendation, totalentries, table_shippingcost, table_category, table_price, table_duration, table_keyword, table_related, graph = scrapy(
                text)
            args = {
                "table_recommendation": table_recommendation,
                "totalentries": totalentries,
                "table_shippingcost": table_shippingcost,
                "table_category": table_category,
                "table_price": table_price,
                "table_duration": table_duration,
                "table_keyword": table_keyword,
                "table_related": table_related,
                "data": graph,
                "text": text
            }

            return render(request, "scrapy/results.html", args)

    form = SearchForm()
    return render(request, "scrapy/results.html", {"form": form})
예제 #11
0
def search(request):

    if request.method == 'POST':

        form = SearchForm(request.POST)
        if form.is_valid():
            upload = form.save(commit=False)
            anon = request.user.is_anonymous
            if anon == False:
                upload.user = request.user
                address = form.cleaned_data['image_address']
                annotated = annotate(address)
                results = page_matches(annotated)
                if len(results) == 0:
                    messages.info(request,
                                  'No other websites contain that image.')
                upload.results = results
                upload.save()
                image = Image.objects.all().get(image_address=address)
                base_url = reverse('results')
                query_string = urlencode({'image': image.id})
                url = '{}?{}'.format(base_url, query_string)
                return redirect(url)
            else:
                address = upload.image_address
                annotated = annotate(address)
                results = page_matches(annotated)
                return render(request, 'results.html', {"results": results})

    else:
        form = SearchForm()
    return render(request, 'search.html', {form: form})
예제 #12
0
def search_whoosh(request):
    if request.method == 'POST':
        form = SearchForm(request.POST)
        if form.is_valid():
            primary_type = form.cleaned_data['primary_type']
            secondary_type = form.cleaned_data['secondary_type']
            generation = form.cleaned_data['generation']
            min_weight = form.cleaned_data['min_weight']
            pokemons = search_pokemon(primary_type, secondary_type, generation,
                                      min_weight)
            return render(request, 'pokemon/pokemon_list.html', {
                'pokemons': pokemons,
                'title': 'Search results'
            })
    else:
        form = SearchForm(initial={'primary_type': '3'})

    return render(request, 'pokemon/form.html', {
        'title': 'Search',
        'form': form,
        'action_url': 'search'
    })
예제 #13
0
파일: views.py 프로젝트: dazzle59/psysite
def articles(request):
    if request.GET:
        form = SearchForm(request.GET)
        context = {'form': form}
        if '_children' in request.GET:
            cat = Category.objects.get(id=3)
            context['article_list'] = Article.objects.filter(category=cat)
            return render(request, 'articles.html', context)
        if '_fears' in request.GET:
            cat = Category.objects.get(id=4)
            context['article_list'] = Article.objects.filter(category=cat)
            return render(request, 'articles.html', context)
        if '_complex' in request.GET:
            cat = Category.objects.get(id=5)
            context['article_list'] = Article.objects.filter(category=cat)
            return render(request, 'articles.html', context)
        if '_other' in request.GET:
            cat = Category.objects.get(id=6)
            context['article_list'] = Article.objects.filter(category=cat)
            return render(request, 'articles.html', context)
        if '_delete' in request.GET:
            context['article_list'] = []
            return render(request, 'articles.html', context)
        if form.is_valid():
            search = form.cleaned_data['search']
            print(search,
                  Article.objects.filter(article_name__icontains=search))
            context['article_list'] = Article.objects.filter(
                article_name__icontains=search)
        else:
            context['error'] = form.errors
            context['article_list'] = None
        return render(request, 'articles.html', context)
    else:
        form = SearchForm(request.GET)
        context = {'form': form}
        context['article_list'] = []
        return render(request, 'articles.html', context)
예제 #14
0
def user_page(request, user_slug):
    """
    Show user page
    :param request: HttpRequest
    :param user_slug: profile.slug
    :return: HttpResponse
    """
    profile = get_object_or_404(UserProfile, slug=user_slug)
    about_reviews = profile.user.reviews.order_by('-created').select_related(
        'author')[:3]
    user_goods = Good.objects.filter(user=profile.user)
    searchform = SearchForm()
    five_count = profile.get_mark_count_about(5)
    four_count = profile.get_mark_count_about(
        4.5) + profile.get_mark_count_about(4)
    three_count = profile.get_mark_count_about(
        3.5) + profile.get_mark_count_about(3)
    two_count = profile.get_mark_count_about(
        2.5) + profile.get_mark_count_about(2)
    one_count = profile.get_mark_count_about(
        1.5) + profile.get_mark_count_about(1)
    average_mark = round(profile.get_about_average_mark(), 1)
    all_to_user_sold_orders = profile.user.my_sold_orders.all().values_list(
        'buyer', flat=True)
    goods_with_max_likes = Good.active.annotate(
        count=Count('users_like')).order_by('-count')[:7]
    return render(
        request, 'user_page.html', {
            'searchform': searchform,
            'profile': profile,
            'about_reviews': about_reviews,
            'user_goods': user_goods,
            'goods_with_max_likes': goods_with_max_likes,
            'five_count': five_count,
            'four_count': four_count,
            'three_count': three_count,
            'two_count': two_count,
            'one_count': one_count,
            'average_mark': average_mark,
            'all_to_user_sold_orders': all_to_user_sold_orders,
            'GOOGLE_GEOCODING_KEY': settings.GOOGLE_GEOCODING_KEY,
            'COMPLAINT_NOT_DEFINED': COMPLAINT_NOT_DEFINED,
            'OWNER_IMPERSONATE': OWNER_IMPERSONATE,
            'FRAUD': FRAUD,
            'SPAM': SPAM,
            'ADVERTISE': ADVERTISE
        })
예제 #15
0
def by_rubric(request, pk):
    rubric = get_object_or_404(SubRubric, pk=pk)
    bbs = Bb.objects.filter(is_active=True, rubric=pk)
    if 'keyword' in request.GET:
        keyword = request.GET['keyword']
        q = Q(title__icontains=keyword) | Q(content__icontains=keyword)
        bbs = bbs.filter(q)
    else:
        keyword = ''
    form = SearchForm(initial={'keyword': keyword})
    paginator = Paginator(bbs, 2)
    if 'page' in request.GET:
        page_num = request.GET['page']
    else: page_num = 1
    page = paginator.get_page(page_num)
    context = {
        'rubric': rubric, 'page': page, 'bbs': page.object_list, 'form': form
    }
    return render(request, 'main/by_rubric.html', context)
예제 #16
0
def user_search(request):
    """
    Show users search page and perform search.
    :param request: HttpRequest if contains query parameter - then perform filtered search. Else - show all users.
    :return: HttpResponse
    """
    search_form = SearchForm()
    if 'query' in request.GET:
        users = filtered_user_search(request.GET)
        # Set page id and url to work with pagination and store request results
        page_id = 'query'
        search_request = request.GET.urlencode()
    else:
        users = User.objects.filter(is_active=True,
                                    is_staff=False).select_related('profile')
        page_id = None
        search_request = None
    tags = Tag.objects.all()
    paginator = Paginator(users, ITEMS_COUNT)
    page = request.GET.get('page')
    try:
        users = paginator.page(page)
    except PageNotAnInteger:
        users = paginator.page(1)
    except EmptyPage:
        if request.is_ajax():
            return HttpResponse('')
        users = paginator.page(paginator.num_pages)
    if request.is_ajax():
        return render(request, 'user_search_ajax.html', {"users": users})
    return render(
        request, 'user_search.html', {
            'search_form': search_form,
            'users': users,
            'LEGAL_ENTITY': LEGAL_ENTITY,
            'PRIVATE_PERSON': PRIVATE_PERSON,
            'MALE': MALE,
            'FEMALE': FEMALE,
            'NOT_DEFINED': NOT_DEFINED,
            'tags': tags,
            'page_id': page_id,
            'search_request': search_request
        })
예제 #17
0
def show_threads_list(request):
    """
    Show thread list
    :param request:
    :return:
    """
    threads = Thread.objects.filter(participants=request.user)
    if threads:
        for thread in threads:
            try:
                thread.partner = thread.participants.exclude(
                    id=request.user.id)[0]
            except IndexError:
                thread.partner = None
    form = SearchForm()
    return render(request, 'threads_list.html', {
        'threads': threads,
        'user': request.user,
        'form': form
    })
예제 #18
0
class SignUpView(TemplateView):
    """
    signup view
    """
    template_name = "user/signup.html"
    signup_form = SignUpValidation()
    board_form = BoardForms()
    team_form = TeamForms()
    search_form = SearchForm()

    def get(self, *args, **kwargs):
        signup_form = SignUpValidation()
        return render(self.request, self.template_name,
                      {'forms': self.signup_form})

    def post(self, *args, **kwargs):
        forms = SignUpValidation(self.request.POST)

        if forms.is_valid():
            user = forms.save()
            user.set_password(forms.cleaned_data.get('password'))
            user.save()

            user = authenticate(username=forms.cleaned_data.get('email'),
                                password=forms.cleaned_data.get('password'))
            login(self.request, user)
            team_form = TeamForms()
            board_form = BoardForms()
            teams = self.request.user.teams.all()
            boards = Board.objects.filter(owner_id=self.request.user.id)

            return render(
                self.request, 'main/home.html', {
                    'board_form': self.board_form,
                    'team_form': self.team_form,
                    'search_form': self.search_form,
                    'teams': teams,
                    'boards': boards
                })

        return render(self.request, self.template_name, {'forms': forms})
예제 #19
0
class LoginView(TemplateView):
    """
    login view
    """
    template_name = "user/login.html"
    login_form = LoginValidation()
    board_form = BoardForms()
    team_form = TeamForms()
    search_form = SearchForm()
    comment_form = CommentForms()

    def get(self, *args, **kwargs):
        # import pdb; pdb.set_trace()
        return render(self.request, self.template_name, {
            'forms': self.login_form,
            'comment_form': self.comment_form
        })

    def post(self, *args, **kwargs):
        forms = LoginValidation(self.request.POST)

        if forms.is_valid():
            user = authenticate(username=forms.cleaned_data.get('email'),
                                password=forms.cleaned_data.get('password'))
            login(self.request, user)
            team_form = TeamForms()
            board_form = BoardForms()
            teams = self.request.user.teams.all()
            boards = Board.objects.filter(owner_id=self.request.user.id)

            return render(
                self.request, 'main/home.html', {
                    'board_form': self.board_form,
                    'team_form': self.team_form,
                    'search_form': self.search_form,
                    'comment_form': self.comment_form,
                    'teams': teams,
                    'boards': boards
                })

        return render(self.request, self.template_name, {'forms': forms})
예제 #20
0
파일: views.py 프로젝트: teamstudios/test
def edit_good(request, good_pk):
    """

    :param request:
    :param good_pk:
    :return:
    """
    # TODO: complete edit view
    search_form = SearchForm()
    image_upload_form = CustomImageUpload()
    good_form = GoodForm()
    properties_form = GoodPropetiesForm()
    all_tags = Tag.objects.all()
    return render(
        request, 'add_good.html', {
            'search_form': search_form,
            'good_form': good_form,
            'image_upload_form': image_upload_form,
            'properties_form': properties_form,
            'all_tags': all_tags
        })
예제 #21
0
def bum(request):
    topic = SearchForm(request.GET, initial={"topic_text": "c"})
    sim_str = topic.cleaned_data.get('topic_text')
    checklist = sim_str.split(",")
    # checklist = topic.cleaned_data.get('symptom')
    try:
        checklist.append(request.POST['symptom1'])
    except:
        pass
    try:
        checklist.append(request.POST['symptom2'])
    except:
        pass
    try:
        checklist.append(request.POST['symptom3'])
    except:
        pass
    try:
        checklist.append(request.POST['symptom4'])
    except:
        pass
    try:
        checklist.append(request.POST['symptom5'])
    except:
        pass
    try:
        checklist.append(request.POST['symptom6'])
    except:
        pass
    try:
        checklist.append(request.POST['symptom7'])
    except:
        pass
    # return HttpResponse(checklist)

    li = ob.search_symptoms(checklist)

    l = len(li)
    return render(request, 'Temp/request2.html', {"list": li, "len": l})
예제 #22
0
파일: views.py 프로젝트: sonhaechang/church
def main_page(request):
    notice = Notice.objects.all()
    weekly = Weekly.objects.all()
    video = Video.objects.all()
    gallery = Gallery.objects.prefetch_related('thumbnail_set').all()
    picture = Picture.objects.prefetch_related('thumbnail_set').all()
    flower = Flower.objects.prefetch_related('thumbnail_set').all()
    school_class = School_Class.objects.all()
    form = SearchForm()

    return render(
        request, 'main/main.html', {
            'notice_list': notice,
            'weekly_list': weekly,
            'video_list': video,
            'gallery_list': gallery,
            'picture_list': picture,
            'flower_list': flower,
            'school_class': school_class,
            'media': settings.MEDIA_URL,
            'search_form': form,
        })
예제 #23
0
def show_thread(request, thread_id):
    """
    Show messages thread
    :param request: HttpRequest
    :param thread_id: Thread id
    :return:
    """
    thread = get_object_or_404(Thread, id=thread_id)
    thread.has_unread = False
    thread.save()
    messages = Message.objects.filter(thread=thread).order_by("datetime")
    try:
        partner = thread.participants.exclude(id=request.user.id)[0]
    except IndexError:
        partner = None
    form = SearchForm()
    return render(
        request, 'thread.html', {
            'thread': thread,
            'messages': messages,
            'partner': partner,
            'user': request.user,
            'form': form
        })
예제 #24
0
 def get_context_data(self, *, object_list=None, **kwargs):
     context = super(MessageView, self).get_context_data(object_list=None,
                                                         **kwargs)
     context['form'] = SearchForm()
     return context
예제 #25
0
def index(request):
    bbs = Bb.objects.all()[:10]
    form = SearchForm()
    return render(request, 'main/index.html', {'bbs': bbs, 'form': form})
예제 #26
0
    def get(self, request):
        form = SearchForm(request.GET)

        ctx = {
            "form": form
        }

        if form.is_valid():
            name_query = form.cleaned_data.get("name")
            if name_query:
                s = Search(index="daintree").query("match", name=name_query)
            else:
                s = Search(index="daintree")

            min_price = form.cleaned_data.get("min_price")
            max_price = form.cleaned_data.get("max_price")
            if min_price is not None or max_price is not None:
                price_query = dict()

                if min_price is not None:
                    price_query["gte"] = min_price

                if max_price is not None:
                    price_query["lte"] = max_price

                s = s.query("range", price=price_query)

            # Add aggregations
            s.aggs.bucket("categories", "terms", field="category")

            if request.GET.get("category"):
                s = s.query("match", category=request.GET["category"])

            result = s.execute()

            ctx["products"] = result.hits

            category_aggregations = list()
            for bucket in result.aggregations.categories.buckets:
                category_name = bucket.key
                doc_count = bucket.doc_count

                category_url_params = request.GET.copy()
                category_url_params["category"] = category_name
                category_url = "{}?{}".format(reverse("home"), category_url_params.urlencode())

                category_aggregations.append({
                    "name": category_name,
                    "doc_count": doc_count,
                    "url": category_url
                })

            ctx["category_aggs"] = category_aggregations

        if "category" in request.GET:
            remove_category_search_params = request.GET.copy()
            del remove_category_search_params["category"]
            remove_category_url = "{}?{}".format(reverse("home"), remove_category_search_params.urlencode())
            ctx["remove_category_url"] = remove_category_url
    
        return render(request, "home.html", ctx)
예제 #27
0
파일: views.py 프로젝트: teamstudios/test
 def get_context_data(self, **kwargs):
     context = super(GoodDeleteView, self).get_context_data(**kwargs)
     context['form'] = SearchForm()
     return context
예제 #28
0
파일: views.py 프로젝트: teamstudios/test
def search_view(request):
    """
    Search view. If 'query' or 'filter' not in request.GET or form is invalid - render index.html.
    Else render  search_categories.html and pass found objects(goods, it's(goods) count and it's sellers(user model).
    If 'filter' in request.Get - perform filtered search
    :param request: HttpRequest with query parameter.
    :return: HttpResponse
    """

    if 'query' in request.GET:
        # Default search by tag or title/description
        form = SearchForm(request.GET)
        if form.is_valid():
            page_id = 'search'  # Set page id (to use in template )
            search_request = form.cleaned_data['query']
            tags = []
            for word in search_request.split(' '):
                tags = list(
                    chain(tags, Tag.objects.filter(name__icontains=word)))
            if tags:
                objects = simple_search(search_request, tags)
            else:
                objects = simple_search(search_request)
            objects_count = objects.count()
            # Store query result in session (just id's)
            request.session['query_result'] = json.dumps(
                list(objects.values_list('id', flat=True)))
        else:
            form = SearchForm()
            return render(request, "index.html", {
                "theme_id": NOT_DEFINED,
                'form': form
            })
    elif 'filter' in request.GET:
        # Filtered search by filter parameters
        search_request = request.GET.urlencode()
        objects = filtered_search(request.GET)
        objects_count = objects.count()
        page_id = 'filter'  # Set page id(to use in template )
        # Store query result in session (just id's)
        request.session['query_result'] = json.dumps(
            list(objects.values_list('id', flat=True)))
    else:
        form = SearchForm()
        return render(request, "index.html", {
            "theme_id": NOT_DEFINED,
            'form': form
        })
    sellers = UserProfile.objects.filter(
        user__goods__in=objects).distinct()[:5]
    paginator = Paginator(objects, ITEMS_COUNT)
    page = request.GET.get('page')
    try:
        objects = paginator.page(page)
    except PageNotAnInteger:
        objects = paginator.page(1)
    except EmptyPage:
        if request.is_ajax():
            return HttpResponse('')
        objects = paginator.page(paginator.num_pages)
    form = SearchForm()
    all_tags = Tag.objects.all()
    if request.is_ajax():
        return render(
            request, 'search_category_ajax.html', {
                "objects": objects,
                'objects_count': objects_count,
                'search_request': search_request,
                'sellers': sellers,
                'form': form,
                'all_tags': all_tags,
            })
    return render(
        request, "search_categories.html", {
            "objects": objects,
            'objects_count': objects_count,
            'search_request': search_request,
            'sellers': sellers,
            'form': form,
            'all_tags': all_tags,
            'page': page_id
        })
예제 #29
0
파일: views.py 프로젝트: sonhaechang/church
def post_search(request):
    if request.method == 'POST':
        form = SearchForm(request.POST)
        if form.is_valid():
            objects_list = []
            schWord = request.POST['search_word']
            last = schWord[:1]
            print(last)
            first = schWord[1:]
            print(first)

            # QnA = QnA.objects.filter(Q(title__icontains=schWord) |
            #     Q(content__icontains=schWord)).distinct()
            # if video.exists():
            #     for i in range(len(QnA)):
            #         objects_list.append(QnA[i])

            notice = Notice.objects.filter(
                Q(title__icontains=schWord) | Q(content__icontains=schWord)
                | Q(user__last_name__icontains=last,
                    user__first_name__icontains=first)).distinct()
            # if notice.exists():
            #     for i in range(len(notice)):
            #         objects_list.append(notice[i])

            weekly = Weekly.objects.filter(
                Q(title__icontains=schWord) | Q(content__icontains=schWord)
                | Q(user__last_name__icontains=last,
                    user__first_name__icontains=first)).distinct()
            # if weekly.exists():
            #     for i in range(len(weekly)):
            #         objects_list.append(weekly[i])

            gallery = Gallery.objects.filter(
                Q(title__icontains=schWord) | Q(content__icontains=schWord)
                | Q(user__last_name__icontains=last,
                    user__first_name__icontains=first)).distinct()
            # if gallery.exists():
            #     for i in range(len(gallery)):
            #         objects_list.append(gallery[i])

            picture = Picture.objects.filter(
                Q(title__icontains=schWord) | Q(content__icontains=schWord)
                | Q(user__last_name__icontains=last,
                    user__first_name__icontains=first)).distinct()
            # if picture.exists():
            #     for i in range(len(picture)):
            #         objects_list.append(picture[i])

            freeboard = Freeboard.objects.filter(
                Q(title__icontains=schWord) | Q(content__icontains=schWord)
                | Q(user__last_name__icontains=last,
                    user__first_name__icontains=first)).distinct()
            # if freeboard.exists():
            #     for i in range(len(freeboard)):
            #         objects_list.append(freeboard[i])

            group = Group.objects.filter(
                Q(title__icontains=schWord) | Q(content__icontains=schWord)
                | Q(user__last_name__icontains=last,
                    user__first_name__icontains=first)).distinct()
            # if group.exists():
            #     for i in range(len(group)):
            #         objects_list.append(group[i])

            video = Video.objects.filter(
                Q(title__icontains=schWord) | Q(content__icontains=schWord)
                | Q(user__last_name__icontains=last,
                    user__first_name__icontains=first)).distinct()
            # if video.exists():
            #     for i in range(len(video)):
            #         objects_list.append(video[i])
            flower = Flower.objects.filter(
                Q(title__icontains=schWord) | Q(content__icontains=schWord)
                | Q(user__last_name__icontains=last,
                    user__first_name__icontains=first)).distinct()

            context = {
                'search_form': form,
                'notice_list': notice,
                'weekly_list': weekly,
                'gallery_list': gallery,
                'picture_list': picture,
                'freeboard_list': freeboard,
                'flower': flower,
                'group_list': group,
                # 'QnA_list': QnA,
                'video_list': video,
                'search_term': schWord,
                'objects_list': objects_list,
            }
            return render(request, 'main/search_form.html', context)
    else:
        form = SearchForm()
    return render(request, 'main/search_form.html', {'search_form': form})
    def get(self, request):
        form = SearchForm(request.GET)
        ctx = {'form': form}
        if form.is_valid():
            name_query = form.cleaned_data['name']
            if name_query:
                search = Search(index='sample_index').query('match',
                                                            name=name_query)
            else:
                search = Search(index='sample_index')

            min_price = form.cleaned_data['min_price']
            max_price = form.cleaned_data['max_price']
            if max_price is not None and min_price is not None:
                price_query = {}
                if max_price is not None:
                    price_query['lte'] = max_price
                if min_price is not None:
                    price_query['gte'] = min_price
                search = search.query('range', price=price_query)

            search.aggs.bucket(
                'categories',
                'terms',
                field='category',
            )

            if request.GET.get('category'):
                search = search.query('match',
                                      category=request.GET['category'])

            result = search.execute()
            ctx['products'] = result.hits

            category_aggregations = list()
            for bucket in result.aggregations.categories.buckets:
                category_name = bucket.key
                doc_count = bucket.doc_count

                category_url_params = request.GET.copy()
                category_url_params['category'] = category_name
                category_url = '{}?{}'.format(
                    reverse('home'),
                    category_url_params.urlencode(),
                )

                category_aggregations.append({
                    'name': category_name,
                    'doc_count': doc_count,
                    'url': category_url
                })

            ctx['category_aggs'] = category_aggregations

        if "category" in request.GET:
            remove_category_search_params = request.GET.copy()
            del remove_category_search_params["category"]
            remove_category_url = "{}?{}".format(
                reverse("home"), remove_category_search_params.urlencode())
            ctx["remove_category_url"] = remove_category_url
        return render(request, 'home.html', ctx)
예제 #31
0
def default(request):
    form = SearchForm()
    return {
        'search_form': form,
    }