예제 #1
0
def index(request):
    '''get:ecトップページを表示 post:検索結果で絞り込んでecトップページを表示'''
    search_form = SearchForm(request.POST or None)
    products = Product.objects.all().order_by('-created_at')
    # 検索フォーム
    if request.method == 'POST':
        if search_form.is_valid():
            user = request.user
            select = search_form.cleaned_data['select']
            keyword = search_form.cleaned_data['keyword']

            # ユーザー選択時の処理
            if select == '友人のみ':
                result_users = []
                if user.is_authenticated:
                    for friend_instance in Friend.objects.filter(owner=user):
                        friend = friend_instance.friends
                        result_users.append(friend)
            if select == '全体':
                user_model = get_user_model()
                result_users = user_model.objects.all()

            searched_products = []
            for result_user in result_users:
                products = Product.objects.filter(owner=result_user)
                for product in products:
                    searched_products.append(product)

            # ワード検索時の処理
            if keyword:
                products = []
                for product in searched_products:
                    name = product.name
                    owner = product.owner.name
                    description = product.description
                    if not description:
                        description = ''
                    text_list = [name, owner, description]
                    text = ' '.join(text_list)
                    if re.findall(keyword, text, re.IGNORECASE):
                        products.append(product)
                messages.success(request, f'"{keyword}"の検索結果({select})')
            if not keyword:
                products = searched_products
                messages.success(request, f'絞り込み({select})')
        else:
            messages.warning(request, '無効な検索です')
            return redirect('ecapp:index')

    num = request.GET.get('page')
    if not num:
        num = 1
    products = Paginator(products, 12)
    products = products.get_page(num)
    context = {'search_form': search_form, 'products': products}
    return render(request, 'ecapp/index.html', context)
예제 #2
0
class SearchView(TemplateView):
    template_name = 'users/search.html'

    @method_decorator(login_required)
    def dispatch(self, request, *args, **kwargs):
        self.form = SearchForm(request.GET or None)
        return super(SearchView, self).dispatch(request, *args, **kwargs)

    def get_filtered_qs(self, qs):
        self.form.is_valid()
        if not hasattr(self.form, 'cleaned_data'):
            return qs
        if self.form.cleaned_data.get('name'):
            query = None
            for val in self.form.get_values_list('name'):
                q = Q(first_name__icontains=val) | Q(last_name__icontains=val)
                if query is None:
                    query = q
                else:
                    query |= q
            if query:
                qs = qs.filter(query)
        if self.form.cleaned_data.get('sex'):
            qs = qs.filter(sex=self.form.cleaned_data['sex'])
        if self.form.cleaned_data.get('by_from'):
            qs = qs.filter(birth_date__gte=datetime.datetime(
                self.form.cleaned_data['by_from'], 1, 1))
        if self.form.cleaned_data.get('by_to'):
            qs = qs.filter(birth_date__lt=datetime.datetime(
                self.form.cleaned_data['by_to'] + 1, 1, 1))
        for field_name in ('city', 'job', 'about_me', 'interests'):
            query = None
            for val in self.form.get_values_list(field_name):
                q = Q(**{'%s__icontains' % field_name: val})
                if query is None:
                    query = q
                else:
                    query |= q
            if query:
                qs = qs.filter(query)
        return qs

    def get_context_data(self, **kwargs):
        context = super(SearchView, self).get_context_data(**kwargs)
        context['form'] = self.form
        qs = self.get_filtered_qs(User.objects.all())
        paginator = Paginator(qs, 20)
        page = self.request.GET.get('page')
        try:
            items = paginator.page(page)
        except PageNotAnInteger:
            items = paginator.page(1)
        except EmptyPage:
            items = paginator.page(paginator.num_pages)
        context['items'] = items
        return context
예제 #3
0
class SearchView(TemplateView):
    template_name = 'users/search.html'

    @method_decorator(login_required)
    def dispatch(self, request, *args, **kwargs):
        self.form = SearchForm(self.request.GET or None)
        return super(SearchView, self).dispatch(request, *args, **kwargs)

    def get_filter_queryset(self, qs):
        self.form.is_valid()
        if not hasattr(self.form, 'cleaned_data'):
            return qs
        if self.form.cleaned_data.get('name'):
            query = None
            for val in self.form.get_values_list('name'):
                q = Q(first_name__icontains=val) | Q(last_name__icontains=val)
                if query is None:
                    query = q
                else:
                    query |= q
            if query:
                qs = qs.filter(query)
        if self.form.cleaned_data.get('sex'):
            qs = qs.filter(sex=self.form.cleaned_data['sex'])
        if self.form.cleaned_data.get('by_from'):
            qs = qs.filter(birth_date__gte=datetime.datetime(self.form.cleaned_data['by_from'], 1, 1))
        if self.form.cleaned_data.get('to_from'):
            qs = qs.filter(birth_date__lt=datetime.datetime(self.form.cleaned_data['to_from']+1, 1, 1))
        for field_name in ('city', 'job', 'about_me', 'interests'):
            query = None
            for val in self.form.get_values_list(field_name):
                q = Q(**{'{}__icontains'.format(field_name): val})
                if query is None:
                    query = q
                else:
                    query |= q
            if query:
                qs = qs.filter(query)
        return qs

    def get_context_data(self, **kwargs):
        context = super(SearchView, self).get_context_data(**kwargs)
        context['form'] = self.form
        qs = self.get_filter_queryset(User.objects.all())
        paginator = Paginator(qs, 20)
        page = self.request.GET.get('page')
        try:
            items = paginator.page(page)
        except PageNotAnInteger:
            items = paginator.page(1)
        except EmptyPage:
            items = paginator.page(paginator.num_pages)
        context['items'] = items
        return context
예제 #4
0
def search_user(request):
    is_young=is_young_check(request)
    is_principal=is_principal_check(request)
    a=datetime.now() - timedelta(seconds=(365.25*24*60*60))
    investigadores=[]

    if request.method=='POST':
        formulario = SearchForm(request.POST)
        if formulario.is_valid():
            text=formulario.cleaned_data["text"]
            filter=formulario.cleaned_data["filter"]
            if (filter=="keyword"):
                qset = (
                    Q(keyword__word=text)&
                    Q(user__last_login__gt=a)
                )
            elif (filter=="research field"):
                qset = (
                    Q(research_field=text)&
                    Q(user__last_login__gt=a)
                )
            elif (filter=="research speciality"):
                qset = (
                    Q(research_speciality=text)&
                    Q(user__last_login__gt=a)
                )

            if formulario.cleaned_data["type"]=="principal":
                investigadores = PrincipalInvestigator.objects.filter(qset).distinct()
            else:
                investigadores = YoungInvestigator.objects.filter(qset).distinct()
            
    else:
        formulario=SearchForm()

    return render_to_response("users/list.html", {
        "results": investigadores,
        "formulario": formulario,
        'is_principal':is_principal,'is_young':is_young,
    },context_instance = RequestContext(request))
예제 #5
0
def search_user(request):
    is_young = is_young_check(request)
    is_principal = is_principal_check(request)
    a = datetime.now() - timedelta(seconds=(365.25 * 24 * 60 * 60))
    investigadores = []

    if request.method == 'POST':
        formulario = SearchForm(request.POST)
        if formulario.is_valid():
            text = formulario.cleaned_data["text"]
            filter = formulario.cleaned_data["filter"]
            if (filter == "keyword"):
                qset = (Q(keyword__word=text) & Q(user__last_login__gt=a))
            elif (filter == "research field"):
                qset = (Q(research_field=text) & Q(user__last_login__gt=a))
            elif (filter == "research speciality"):
                qset = (Q(research_speciality=text)
                        & Q(user__last_login__gt=a))

            if formulario.cleaned_data["type"] == "principal":
                investigadores = PrincipalInvestigator.objects.filter(
                    qset).distinct()
            else:
                investigadores = YoungInvestigator.objects.filter(
                    qset).distinct()

    else:
        formulario = SearchForm()

    return render_to_response("users/list.html", {
        "results": investigadores,
        "formulario": formulario,
        'is_principal': is_principal,
        'is_young': is_young,
    },
                              context_instance=RequestContext(request))
예제 #6
0
def home(request):
    api_key='ICFTK388eCNp493fEzwT-hwJCHgGKZi-Hjs-ZNVMThBBzPDduzs8Pya_WCs7tSSAnjqUPjmwrAhMXy3kC3wZlnCnpNo31qgMSSsEjLGW6dP6w09xMlMrX19sCbQcX3Yx'
    url = 'https://api.yelp.com/v3/businesses/search?categories=bars&location={}&reviews?sort_by=rating'
    headers = {'Authorization': 'Bearer %s' % api_key}
    params = {
        'limit': 20,
        'radius': 10000,
        'offset': 50

    }
    form = SearchForm()
    if request.method == "GET":
        form = SearchForm(request.GET or None)
        if form.is_valid():
            # Append user entry (zip code) onto the endpoint url
            zc = form.cleaned_data["zip_code"]

            # Save the json dictionary to business_data
            try:
                business_data = requests.get(url.format(zc), headers=headers, params=params).json()
            except requests.exceptions.RequestException:
                #Handle incase you're unable to get the response
                redirect('about/')
                
            else:
                # Re-instantiate the form after it's submitted
                form = SearchForm()

                # Save the json response into a new dictionary
                context = {
                    'businesses': business_data['businesses']
                }
                
                print(context)
                # Return the data so that it is available for the home page template
                return render(request, 'blog/home.html', context)     
    else:
        redirect('/')
    
    return render(request, 'blog/home.html', {"form": form})      
예제 #7
0
 def dispatch(self, request, *args, **kwargs):
     self.form = SearchForm(self.request.GET or None)
     return super(SearchView, self).dispatch(request, *args, **kwargs)
예제 #8
0
def about(request):
    form = SearchForm()
    return render(request, 'blog/about.html', {'form': form})
예제 #9
0
def index(request):
    '''get:snsトップページを表示 post:検索結果で絞り込んでsnsトップページを表示'''
    search_form = SearchForm(request.POST or None)
    articles = Article.objects.all().order_by('-created_at')
    # 検索フォーム
    if request.method == 'POST':
        if search_form.is_valid():
            user = request.user
            select = search_form.cleaned_data['select']
            keyword = search_form.cleaned_data['keyword']

            # ユーザー選択時の処理
            if select == '友人のみ':
                result_users = []
                if user.is_authenticated:
                    for friend_instance in Friend.objects.filter(owner=user):
                        friend = friend_instance.friends
                        result_users.append(friend)
            if select == '全体':
                user_model = get_user_model()
                result_users = user_model.objects.all()

            searched_articles = []
            for result_user in result_users:
                articles = Article.objects.filter(author=result_user)
                for article in articles:
                    searched_articles.append(article)

            # ワード検索時の処理
            if keyword:
                articles = []
                for article in searched_articles:
                    author = article.author.name
                    content = article.content
                    product = article.product
                    if product:
                        product = product.name
                    else:
                        product = ''
                    text_list = [author, content, product]
                    text = ' '.join(text_list)
                    if re.findall(keyword, text, re.IGNORECASE):
                        articles.append(article)
                messages.success(request, f'"{keyword}"の検索結果({select})')
            if not keyword:
                articles = searched_articles
                messages.success(request, f'絞り込み({select})')
        else:
            messages.warning(request, '無効な検索です')
            return redirect('snsapp:index')

    num = request.GET.get('page')
    if not num:
        num = 1
    articles = Paginator(articles, 20)
    articles = articles.get_page(num)
    context = {
        'search_form': search_form,
        'articles': articles,
        'next': 'sns',
    }
    return render(request, 'snsapp/index.html', context)
예제 #10
0
 def dispatch(self, request, *args, **kwargs):
     self.form = SearchForm(request.GET or None)
     return super(SearchView, self).dispatch(request, *args, **kwargs)