def search(request,words,list_per_page,page_index): form=SearchForm(action=url_for('core/search_post')) data=Moshimo.get_by_search_word(words,list_per_page,page_index) data['categories']=[u'検索',words] data['form']=form.as_widget() return render_to_response('core/product_list.html', data)
def search(request): if request.method == 'GET': return render(request, 'search.html') else: form = SearchForm(request.POST) if form.is_valid(): query = form.cleaned_data['query'] parameter = form.cleaned_data['parameter'] if parameter == 'Tümü' and query is not None: results = ItbookApi(query).get_result() return render(request, 'result.html', { 'query': query, 'results': results }) elif parameter == 'İsim' and query is not None: results = search_by_name(query) return render(request, 'result.html', { 'query': query, 'results': results }) else: messages.error(request, 'Invalid search entry.') return HttpResponseRedirect('/') else: messages.error(request, 'Invalid search entry.') return HttpResponseRedirect('/')
def tags(request,tags,list_per_page,page_index): form=SearchForm(action='/search_post') data=Moshimo.get_by_tags(tags,list_per_page,page_index) data['categories']=[u'タグ',tags] data['form']=form.as_widget() return render_to_response('core/product_list.html',data)
def get_queryset(self): params = {} #import pdb;pdb.set_trace() form = SearchForm(self.request.user.rep, self.request.GET) if form.is_valid(): start = form.cleaned_data['start'] end = form.cleaned_data['end'] rep = form.cleaned_data['rep'] date_fld = self.order_by if date_fld[0] == '-': date_fld = date_fld[1:] #params.update({'{}__range'.format(date_fld): (start, end)}) if start: params.update({'{}__gte'.format(date_fld): start}) if end: params.update({'{}__lte'.format(date_fld): end}) if rep: params.update({'rep': rep}) else: #subordinates = [r for r in Rep.objects.filter(supervisor=rep)] #all_reps = [rep] + subordinates #params.update({'rep__in': all_reps}) params.update({'rep': self.request.user.rep}) ordering = [self.order_by] if self.order_by_extra: ordering.append(self.order_by_extra) return self.model.objects.filter(**params).order_by(*ordering)
def detail(request,article_id): from core.models import Product form=SearchForm(action='/search_post') data=Moshimo.get_by_article_id(article_id) data['form']=form.as_widget() return render_to_response('core/detail.html', data)
def list_companies(req, startchar=''): if req.method == 'POST': form = SearchForm(req.POST) if form.is_valid(): s = form.cleaned_data['search'] companies = Company.objects.select_related().filter( Q(name__icontains=s) | Q(short_name__icontains=s)) else: companies = Company.objects.none() messages.error(req, u'Ungültige Suche.') else: form = SearchForm() if not startchar: companies = Company.objects.select_related().all() for c in string.ascii_uppercase: companies = companies.exclude(name__istartswith=c) else: companies = Company.objects.select_related().filter( name__istartswith=startchar) companies = companies.exclude(**settings.EXCLUDE_FROM_COMPANY_LIST) ptitle = u'Firmen: {0} ({1})'.format( startchar or '-', companies.count() ) ctx = dict( page_title=ptitle, companies=companies, menus=menus, chars=string.ascii_uppercase, form=form, single_view=False ) return render(req, 'companies/list.html', ctx)
def search_question(request): """ For searching question via regex and tags """ if request.method == "GET": form = SearchForm() questions = Question.objects.all() context = { 'form': form, 'questions': questions, } return render(request, 'core/search_question.html', context=context) if request.method == "POST": form = SearchForm(request.POST or None) context = {} if form.is_valid(): title = form.cleaned_data['title'] tags = form.cleaned_data['tags'] if not tags: qu = Question.objects.filter(title__icontains=title) else: qu = Question.objects.filter(title__icontains=title).filter( tags__name__in=tags).distinct() context['questions'] = qu context['form'] = form return render(request, 'core/search_question.html', context=context)
def products(request,category_code,list_per_page,page_index): form=SearchForm(action='/search_post') data=Moshimo.get_by_category(category_code,list_per_page,page_index) data['categories']=Moshimo.get_category_name(category_code) data['form']=form.as_widget() return render_to_response('core/product_list.html',data)
def product(request): from core.forms import ProductForm from core.forms import SearchForm product_form=ProductForm() search_form=SearchForm() if request.method=='POST' and product_form.validate(request.form): product_form.save(key_name=form['article_id']) return render_to_response('admin/product.html', {'form':search_form.as_widget(),'product_form': product_form.as_widget()})
def index(request): translations = [] short_name = 1 query = '' results = [] if "query" in request.GET: form = SearchForm(request.GET) is_searching = True if form.is_valid(): query = form.cleaned_data['query'] short_name = form.cleaned_data['languages'] translations = Translation.objects.filter( sentence__msgid__icontains=query, language__short_name=short_name, obsolete=False, ).values( 'sentence__msgid', 'msgstr', 'sentence__length', 'package__name', ).order_by('sentence__length', 'sentence__msgid', 'msgstr').distinct() for trans in translations: """ # I don't like this but for now it's ok packages = Translation.objects.filter( language__short_name=short_name, sentence__msgid=trans['sentence__msgid'] ).order_by( 'package__name' ) """ results.append({ 'msgid': trans['sentence__msgid'], 'msgstr': trans['msgstr'], 'packages': [ trans['package__name'], ] }) else: form = SearchForm() is_searching = False variables = RequestContext( request, { 'object_list': results, 'query': query, 'short_name': short_name, 'form': form, 'is_searching': is_searching, }) return render_to_response('translations/translation_list.html', variables)
def search_post(request): form=SearchForm(action=url_for('core/search_post')) words=None if request.method=='POST' and form.validate(request.form): words=form['words'].strip() words=words.replace('/',' ') if words is None: return redirect(url_for('core/index')) else: return redirect(url_for('core/search',words=words,list_per_page=24,page_index=0))
def sitemap(request): from admin.forms import SitemapForm from core.forms import SearchForm from core.models import Sitemap from google.appengine.ext import deferred sitemap_form=SitemapForm() search_form=SearchForm() if request.method=='POST' and sitemap_form.validate(request.form): if form['mode']==u'更新': deferred.defer(Sitemap.update_article_id,form['article_id']) else: deferred.defer(Sitemap.set_article_id,form['article_id']) return render_to_response('admin/sitemap.html', {'form':search_form.as_widget(),'sitemap_form': sitemap_form.as_widget()})
def index_view(request): if request.GET: form = SearchForm(request.GET) dogs = form.search() else: form = SearchForm() dogs = Dog.objects.all() response = render(request, 'core/index.html', { "dogs": dogs, "search_form": form, }) return response
def pools(request): context = RequestContext(request) resultados = [] usuario = request.user analytics.identify(user_id=usuario.pk, traits={ 'email': usuario.email, 'firstName': usuario.first_name, 'lastName': usuario.last_name, 'createdAt': usuario.date_joined.isoformat() }) if request.method == 'POST': search_form = SearchForm(request.POST) if search_form.is_valid(): try: resultados = Pool.objects.filter( origen=search_form.cleaned_data['origen'], destino=search_form.cleaned_data['destino']) analytics.track( usuario.pk, 'Busca ruta', { 'origen': search_form.cleaned_data['origen'], 'destino': search_form.cleaned_data['destino'] }) except Exception as e: print type(e) print e.args print e else: print search_form.errors colonias = Colonia.objects.all() return render_to_response( 'pools.html', { 'resultados': resultados, 'colonias': colonias, 'pageType': 'Listado Pools' }, context)
def search_docs(request): upload_docs() if request.method == 'POST': form = SearchForm(request.POST) if form.is_valid(): ser_num = form.cleaned_data["ser_num"] if len(ser_num) == 9: ser_num.strip() ser = ser_num[:2] num = ser_num[2:] docs = LostDocuments.objects.filter(series=ser, doc_num=num) return render(request, "core/results.html", {"docs": docs}) else: form = SearchForm() return render(request, 'core/index.html', {'form': form})
def player_search(request): if not request.method == 'POST': return render(request, 'core/index.html') form = SearchForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] platform = form.cleaned_data['platforms'] communication = get_profile_data(username, platform) if communication.error: messages.add_message( request, messages.ERROR, f'Usuário <strong>{username}</strong> não encontrado. ' 'Confira os dados ou selecione outra plataforma.') return redirect(request.META.get('HTTP_REFERER')) return redirect('core:player-detail', username=communication.player_stats.player.username)
def search(request): if request.method == 'POST': form = SearchForm(request.POST) if form.is_valid(): search_string = form.cleaned_data['search_string'] s = SphinxClient() s.SetServer('192.168.102.2', 9312) s.SetLimits(0, 100) if s.Status(): res = s.Query(search_string) return render(request, 'search.html', { 'items': res, 'form': form }) form = SearchForm() return render(request, 'search.html', {'form': form})
def get(self): words = db.Query(WordModel).order('-count').fetch(limit=100) form = SearchForm(self) # context = { # words: words, # # form: form # } self.render("index.html", words=words)
def search_class(request): if request.method == 'POST': form = SearchForm(request.POST) if form.is_valid(): # post = form.save(commit=False) depname = form.cleaned_data.get('department') data = Subject.objects.filter(department=depname) # return HttpResponse(depname) return render(request, 'search.html', { 'form': form, 'depname': depname, 'data': data }) else: return HttpResponse("Error in form") else: form = SearchForm() return render(request, 'search.html', {'form': form})
def home_page(request): if request.method == "POST": form = SearchForm(request.POST) else: form = SearchForm() categories = Category.objects.all() products_query = EShopItem.objects.filter(is_on_sale=True) products_query = products_query.filter(current_stock__gte=1) products = products_query[:2] message_query = Message.objects.filter(topic__board__name="news") message_query = message_query.filter(topic__title="main") message = message_query.order_by("-id")[0] return render_to_response("home.html", { 'search_form': form, 'categories': categories, 'promotion_items': products, "message": message }, context_instance=RequestContext(request))
def pools(request): context = RequestContext(request) resultados = [] usuario = request.user analytics.identify(user_id=usuario.pk, traits={ 'email': usuario.email, 'firstName': usuario.first_name, 'lastName': usuario.last_name, 'createdAt': usuario.date_joined.isoformat() }) if request.method == 'POST': search_form = SearchForm(request.POST) if search_form.is_valid(): try: resultados = Pool.objects.filter(origen=search_form.cleaned_data['origen'], destino=search_form.cleaned_data['destino']) analytics.track(usuario.pk, 'Busca ruta', { 'origen': search_form.cleaned_data['origen'], 'destino': search_form.cleaned_data['destino'] }) except Exception as e: print type(e) print e.args print e else: print search_form.errors colonias = Colonia.objects.all() return render_to_response('pools.html', {'resultados': resultados, 'colonias': colonias, 'pageType': 'Listado Pools'}, context)
def search_it(request, template_name='core/home.html'): search = '' #add in the slug maker form = SearchForm(request.POST) # A form bound to the POST data if form.is_valid(): # All validation rules pass form.process() search = form.cleaned_data['title'] slug = slugify(search) try: e = Den.objects.get(slug=slug) except ObjectDoesNotExist: den = form.save(commit=False) den.save() #Spider Tasks t = TaskUtils() t.run_spiders(NewsWebsite, 'scraper', 'scraper_runtime', 'article_spider', search) return redirect('den/' + slug) return render(request, template_name, {'form': form,})
def index(request): u""" トップページ 新入荷商品:Moshimo.get_new_item ヒット商品:Moshimo.get_sales_item """ from moshimo import Moshimo from core.forms import SearchForm from kay.utils import render_to_response form=SearchForm(action='/search_post') salesitem_data=Moshimo.get_sales_item() newitem_data=Moshimo.get_new_item() return render_to_response('core/index.html', { 'form':form.as_widget(), 'newitem':newitem_data, 'salesitem':salesitem_data, })
def index_view(request): if request.GET: form = SearchForm(request.GET) dogs = form.search() else: form = SearchForm() dogs = Dog.objects.all() if request.GET.get('sort'): dogs = dogs.order_by(request.GET.get('sort')) paginator = Paginator(dogs, 6) page = request.GET.get('page', 1) dogs = paginator.get_page(page) response = render(request, 'core/index.html', { "dogs": dogs, "search_form": form, }) return response
def home(request): if request.user.is_authenticated(): # render a user specified web page # assign administrator as super user # assign translator as staff if request.user.is_superuser: return None else: return customer(request, request.user) else: return render(request, 'index.html', {'form': SearchForm()})
def index(request): if request.method == "POST": form = SearchForm(request.POST) if form.is_valid(): files_from_content = [] files_saved = File.objects.filter( name__icontains=form.cleaned_data["file_name"]).values_list( "id", flat=True) files_from_content.extend(files_saved) results = es.search( index="", body={ "query": { "query_string": { "query": form.cleaned_data["file_name"] } } }, ) if results["hits"]["total"]["value"] > 0: for result in results["hits"]["hits"]: files_from_content.append(result["_source"]["file_id"]) files = list( File.objects.filter(id__in=list(set(files_from_content)))) return render( request, "index.html", { "show_files": True, "files_saved": files }, ) files_saved = list(File.objects.all()) return render(request, "index.html", { "show_files": True, "files_saved": files_saved })
def get_context_data(self, **kwargs): kwargs.update({ 'query': self.query, 'short_name': self.short_name, 'form': SearchForm(self.request.GET or None), 'is_searching': ('query' in self.request.GET and 'languages' in self.request.GET), 'pagination_extra': urlencode({ 'languages': self.short_name, 'query': self.query, }), }) return super(SearchableTranslationListView, self).get_context_data(**kwargs)
def new_search(request): if request.method == 'POST': forms = SearchForm(request.POST) if forms.is_valid(): stuff_to_frontend = searching(forms.cleaned_data['search']) forms.save() return render(request, 'core/search.html', context={ 'forms': forms, 'content_data': stuff_to_frontend }) else: forms = SearchForm() # BUG: Debug forms widgets need to change # import pdb; import pdb; pdb.set_trace() return render(request, 'core/search.html', context={'forms': forms})
def customer(request, user): customer = Customer.objects.get(user=user) return render(request, 'customer.html', { 'customer': customer, 'form': SearchForm() })
def test_search_form_field_text_input(self): """test_search_form_field_text_input() should return text input.""" form = SearchForm(initial={'query': 'USS First'}, ) self.assertEqual(form['query'].value(), 'USS First')
def test_search_form_validation(self): """test_search_form_validation() checks form with is_valid() method.""" form_data = {'query': 'something'} form = SearchForm(data=form_data) self.assertTrue(form.is_valid())
def get_context_data(self, **kwargs): context = super(BaseActivityListView, self).get_context_data(**kwargs) form = SearchForm(self.request.user.rep, self.request.GET) context.update({'form': form}) return context
def main(request): form = SearchForm() return render(request, 'index.html', {'form': form})
def before_request(): if current_user.is_authenticated: current_user.last_seen = datetime.utcnow() db.session.commit() g.search_form = SearchForm() g.locale = str(get_locale())
def index(request): from core.forms import SearchForm form=SearchForm() return render_to_response('admin/index.html',{'form':form.as_widget()})
def search_form(request): form = SearchForm(request) if form.is_valid(): form.search() return form
def test_form_renders(self): """test_form_renders() tests input attributes render by HTML.""" form = SearchForm() self.assertIn('class="form-control form-control-lg"', form.as_p())
def search_form(): form = SearchForm() return { 'form': form, }
def browse(request, id=-1): if id is not -1: # Browse book interface. try: sale = Sale.objects.get(id=id, status=Sale.PENDING) except: return error_page(request, "A sale with the id %d could not be " "found." % int(id)) viewer = "guest" if request.user == sale.merchant: viewer = "merchant" elif request.user.is_authenticated(): if len(Offer.objects.filter(sale=sale, status=Sale.PENDING, buyer=request.user)) > 0: viewer = "made_offer" else: viewer = "no_offer" offers = Offer.objects.filter(sale=sale, status=Offer.PENDING).order_by("-price", "buyer__first_name") return load_page(request, "sale_details.html", {"viewer": viewer, "sale": sale, "offers": offers}) else: if request.user.is_authenticated(): sales = Sale.objects.exclude(merchant=request.user).filter(status=Sale.PENDING) else: sales = Sale.objects.filter(status=Sale.PENDING) sales = sales.order_by("price", "title", "merchant__last_name") error = "" title = "" isbn = "" course = "" form = SearchForm(request.GET) if form.is_valid(): title = form.cleaned_data["title"] or "" isbn = form.cleaned_data["isbn"] or "" course = form.cleaned_data["course"] or "" if title != "": sales = sales.filter(title__icontains=title) if isbn != "": sales = sales.filter(isbn__exact=isbn) if course != "": sales = sales.filter(course__exact=course) my_sales = [] for sale in sales: offers = Offer.objects.filter(sale=sale) this_sale = { "id": sale.id, "image": sale.image, "title": sale.title, "course": sale.course, "price": sale.price, "merchant": sale.merchant, "offers": len(offers.filter(status=Offer.PENDING)), "expires": sale.expires, "expires_soon": (sale.expires - date.today()) <= timedelta(1), } my_sales.append(this_sale) sales = my_sales per_page = 5 pages = int(ceil(len(sales) / float(per_page))) page = int(request.GET.get("page", 1)) if pages <= 0: pages = 1 if page <= 0: page = 1 if page > pages: page = pages prev = "?title=%s&isbn=%s&course%s=&page=%s" % (title or "", isbn or "", course or "", (page - 1)) next = "?title=%s&isbn=%s&course=%s&page=%s" % (title or "", isbn or "", course or "", (page + 1)) # Calculate the page number. Don't forget any leftovers on the last page. # page_number = min(page, ceil(len(sales) / float(per_page))) # Calculate the display indices from the page number. first = int((page - 1) * per_page) last = int(page * per_page) sales = sales[first:last] return load_page( request, "browse.html", {"sales": sales, "form": form, "error": error, "prev": prev, "next": next, "page": page, "pages": pages}, )