本文整理汇总了Python中search.forms.SearchForm类的典型用法代码示例。如果您正苦于以下问题:Python SearchForm类的具体用法?Python SearchForm怎么用?Python SearchForm使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了SearchForm类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: search
def search(request):
res_list = []
for res in RESOURCE_CHOICES:
res_list.append({'title': res[0], 'value': res[1]})
form = SearchForm(request.GET)
location_path = None
if form.is_valid():
last_name = form.cleaned_data['last_name']
country = form.cleaned_data['country']
region = form.cleaned_data['region']
district = form.cleaned_data['district']
resource = form.cleaned_data['resource']
location = Location.objects.get(country=None)
if country:
qs = Location.objects.filter(country=country)
if qs.count() > 0:
location = qs[:1].get()
if region:
qs = Location.objects.filter(region=region)
if qs.count() > 0:
location = qs[:1].get()
if district:
qs = Location.objects.filter(district=district)
if qs.count() > 0:
location = qs[:1].get()
# Filter by part of last_name
qfilter = Q()
if last_name != '':
qfilter &= Q(last_name__icontains=last_name)
if resource and resource!='all' and resource!='':
qfilter &= Q(provided_resources__resource__icontains=resource)
# Filter by resource
participants = location.get_entities('participants', qfilter)
ctx = table_data(request, 'participants', participants)
if country or region or district:
location_path = location.path()
ctx['last_name'] = last_name
ctx['country'] = country
ctx['region'] = region
ctx['district'] = district
ctx['resource'] = resource
else:
participants = Location.objects.get(country=None).get_entities('participants')
ctx = table_data(request, 'participants', participants)
ctx['locationWidget'] = LocationSelectWidget().render('location_select', location_path or [])
ctx['resources'] = res_list
return render_to_response('search.html', context_instance=RequestContext(request, ctx))
开发者ID:mikpanko,项目名称:grakon,代码行数:60,代码来源:views.py
示例2: index
def index(request):
# if this is a POST request we need to process the form data
# dump()
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = SearchForm(request.POST)
# check whether it's valid:
if form.is_valid():
print("here")
# process the data in form.cleaned_data as required
# ...
# redirect to a new URL:
zipcode = form.cleaned_data["zipcode"]
hosp_type = form.cleaned_data["hosp_type"]
emergency = form.cleaned_data["emergency"]
criteria = form.cleaned_data["criteria"]
print(form.errors)
data = rank(zipcode, hosp_type, emergency, criteria)
return render(request, "search/result.html", {'form': form, 'data': data})
# else:
# print("invalid form")
# print(form.errors)
# if a GET (or any other method) we'll create a blank form
else:
form = SearchForm()
return render(request, "search/index_.html", {'form': form})
开发者ID:bharathramh92,项目名称:CharlotteHack,代码行数:28,代码来源:views.py
示例3: index
def index(request):
accept = request.META.get('HTTP_ACCEPT_LANGUAGE', '')
user_langs = get_user_languages_from_request(request)
if 'q' in request.REQUEST:
form = SearchForm(request.user, user_langs, request.REQUEST)
else:
form = SearchForm(request.user, user_langs)
qs = SearchQuerySet().none()
display_mode = 'all'
if form.is_valid():
qs = form.search_qs(SearchQuerySet().models(Video))
display_mode = form.cleaned_data.get('display', 'all')
if settings.HAYSTACK_SEARCH_ENGINE == 'dummy' and settings.DEBUG:
q = request.REQUEST.get('q', '')
qs = Video.objects.filter(title__icontains=q)
context = {
'query': request.REQUEST.get('q', ''),
'form': form,
'display_mode': display_mode
}
return object_list(request, queryset=qs,
paginate_by=30,
template_name='search/index.html',
template_object_name='result',
extra_context=context)
开发者ID:MechanisM,项目名称:mirosubs,代码行数:32,代码来源:views.py
示例4: search
def search(request):
"""Search through the experiments for a search term."""
form = SearchForm(request.POST or None)
if not form.is_valid():
return render_to_response("search.html", {"form": form},
context_instance=RequestContext(request))
results = set()
if form.cleaned_data['expt_type']:
expt_type = form.cleaned_data.pop('expt_type')
experiments = Experiment.objects.filter(expt_type__type_name=expt_type)
results = _intersect_unless_empty(results, experiments)
if form.cleaned_data['transcription_factor']:
try:
tf = json.loads('"%s"' % form.cleaned_data['transcription_factor'])
experiments = Experiment.objects.filter(transcription_factor__tf=tf)
form.cleaned_data.pop('transcription_factor')
except ValueError:
tfs = json.loads(form.cleaned_data.pop('transcription_factor'))
experiments = set()
for tf in tfs:
experiments = experiments.union(set(Experiment.objects.filter(transcription_factor__tf=tf)))
results = _intersect_unless_empty(results, experiments)
if form.cleaned_data['tissue_name']:
tissue = form.cleaned_data.pop('tissue_name')
experiments = Experiment.objects.filter(experimental_tissues=tissue)
results = _intersect_unless_empty(results, experiments)
for key, value in form.cleaned_data.iteritems():
if value:
these_results = Experiment.objects.filter(**{key: value})
results = _intersect_unless_empty(results, these_results)
return HttpResponse(str(list(results)))
开发者ID:tmushayahama,项目名称:tftarget,代码行数:34,代码来源:views.py
示例5: get_context_data
def get_context_data(self, **kwargs):
data = super(MainView, self).get_context_data(**kwargs)
posts = Post.objects.filter(parent=None).order_by('-date_created')[:15]
form = SearchForm(self.request.GET or None)
if form.is_valid():
posts = form.search()
data['posts'] = posts
data['form'] = form
return data
开发者ID:kecebongsoft,项目名称:gdifbgroup_archive,代码行数:11,代码来源:views.py
示例6: product_search_view
def product_search_view(request):
post_data = request.POST.copy()
form = SearchForm(data=post_data)
params = request.GET.copy()
if form.is_valid():
q = form.cleaned_data['q']
category_slug = form.cleaned_data.get('category_slug', '')
url = reverse('catalogue_category', kwargs={'category_slug': category_slug})
params['search'] = q
return HttpResponseRedirect(url + "?" + urllib.urlencode(params))
return HttpResponseRedirect(post_data['from'] + "?" + urllib.urlencode(params))
开发者ID:arthurcode,项目名称:arthurcode,代码行数:11,代码来源:views.py
示例7: test_search1
def test_search1(self):
for title in self.titles:
video = Video.objects.all()[0]
sqs = SearchQuerySet().models(Video)
video.title = title
video.save()
reset_solr()
result = SearchForm.apply_query(video.title, sqs)
self.assertTrue(video in [item.object for item in result], u"Failed to find video by title: %s" % title)
result = SearchForm.apply_query(u'BBC', sqs)
self.assertTrue(video in [item.object for item in result], u"Failed to find video by 'BBC' with title: %s" % title)
开发者ID:adncentral,项目名称:unisubs,代码行数:13,代码来源:tests.py
示例8: search
def search(request, tag_name=None, template=None):
# If the form is invalid we still want to have a query.
query = request.REQUEST.get('q', '')
search_opts = {
'meta': ('versions', 'categories', 'tags', 'platforms'),
'version': None,
}
form = SearchForm(request)
form.is_valid() # Let the form try to clean data.
category = form.cleaned_data.get('cat')
if category == 'collections':
return _collections(request)
elif category == 'personas':
return _personas(request)
# TODO: Let's change the form values to something less gross when
# Remora dies in a fire.
query = form.cleaned_data['q']
addon_type = form.cleaned_data.get('atype', 0)
tag = tag_name if tag_name is not None else form.cleaned_data.get('tag')
if tag_name:
search_opts['show_personas'] = True
page = form.cleaned_data['page']
sort = form.cleaned_data.get('sort')
search_opts['version'] = form.cleaned_data.get('lver')
search_opts['limit'] = form.cleaned_data.get('pp', DEFAULT_NUM_RESULTS)
search_opts['platform'] = form.cleaned_data.get('pid', amo.PLATFORM_ALL)
search_opts['sort'] = sort
search_opts['app'] = request.APP.id
search_opts['offset'] = (page - 1) * search_opts['limit']
if category:
search_opts['category'] = category
elif addon_type:
search_opts['type'] = addon_type
search_opts['tag'] = tag
client = SearchClient()
try:
results = client.query(query, **search_opts)
except SearchError, e:
log.error('Sphinx Error: %s' % e)
return jingo.render(request, 'search/down.html', locals(), status=503)
开发者ID:LittleForker,项目名称:zamboni,代码行数:51,代码来源:views.py
示例9: results
def results(request):
url = urllib.unquote_plus(request.get_full_path())
print url
searchform = SearchForm(request.GET)
if not "q" in request.GET:
return redirect('search.views.index')
if searchform.is_valid():
q = searchform.cleaned_data['q']
selected_facets = request.GET.getlist("selected_facets")
remove_facets = request.GET.getlist("remove_facets")
applied_facets = {}
if remove_facets:
for r in remove_facets:
filter(lambda a: a != r, selected_facets)
filter(lambda a: a != r, applied_facets)
if selected_facets:
for f in selected_facets:
k, v = f.split(":")
myurl = url.replace("&selected_facets=%s" % f, "")
tag = "%s : %s" % (k.upper(), v)
applied_facets[tag] = myurl
print applied_facets
if q:
sqs = SearchQuerySet().models(Part).models(Company).facet('brand').facet('category').facet('with_distributors').facet('with_image').auto_query(q)
for facet in selected_facets:
sqs = sqs.narrow(facet)
try:
page = request.GET.get('page', 1)
except PageNotAnInteger:
page = 1
p = Paginator(sqs, 10, request=request)
results_list = p.page(page)
return render_to_response('search/results.html',
{
'results_list': results_list,
'query': q,
'facets': sqs.facet_counts(),
'applied_facets': applied_facets,
},
context_instance=RequestContext(request))
开发者ID:phrac,项目名称:partflux,代码行数:50,代码来源:views.py
示例10: test_search
def test_search(self):
reset_solr()
sqs = SearchQuerySet().models(Video)
qs = Video.objects.exclude(title='')
self.assertTrue(qs.count())
for video in qs:
result = SearchForm.apply_query(video.title, sqs)
self.assertTrue(video in [item.object for item in result])
开发者ID:adncentral,项目名称:unisubs,代码行数:9,代码来源:tests.py
示例11: test_search_funcionality
def test_search_funcionality(self):
NewsFactory(subject='Test Search')
EventFactory(title='Test Search')
response = self.client.get('search', {'query': 'search'})
self.assertEquals(200, response.status_code)
self.assertEquals(1, len(response.context['news']))
self.assertEquals(1, len(response.context['events']))
response = self.client.post('search', {'query': '1'})
from search.forms import SearchForm
form = SearchForm({'query': '1234'})
self.assertTrue(form.is_valid())
form = SearchForm({'query': '1'})
self.assertFalse(form.is_valid())
开发者ID:Narayanan170,项目名称:kset-org,代码行数:18,代码来源:events_test.py
示例12: index
def index(request):
context = RequestContext(request)
gmap = maps.Map(opts = {
'mapTypeId': maps.MapTypeId.ROADMAP,
'zoom': 7,
'mapTypeControlOptions': {
'style': maps.MapTypeControlStyle.DROPDOWN_MENU
},
})
converted=""
if request.method == 'POST':
form = SearchForm(request.POST)
if form.is_valid():
new_obj = Destination()
new_obj.category_id = 1
searchlocation = form.cleaned_data['searchfor']
geoloc = Geocoder.geocode(searchlocation)[0]
converted = str(geoloc)
print(converted)
lat, lng = geoloc.coordinates
marker = maps.Marker(opts = {
'map': gmap,
'position': maps.LatLng(lat, lng),
})
maps.event.addListener(marker, 'mouseover', 'myobj.markerOver')
maps.event.addListener(marker, 'mouseout', 'myobj.markerOut')
info = maps.InfoWindow({
'content': 'Hello!',
'disableAutoPan': True
})
info.open(gmap, marker)
#new_obj.save();
form = SearchForm()
else:
print form.errors
else:
form = SearchForm()
dict = {'form': SearchForm(initial={'map': gmap}), 'converted': converted}
return render_to_response('search/index.html', dict, context);
开发者ID:ajutscaria,项目名称:ajutscaria.github.io,代码行数:42,代码来源:views.py
示例13: results
def results(request):
start = time.time()
searchform = SearchForm(request.GET)
if not "q" in request.GET:
return render_to_response('search/search.html', context_instance=RequestContext(request))
if searchform.is_valid():
q = searchform.cleaned_data['q']
if q:
try:
""" Redirect to a lot number if found """
report = Report.objects.get(lot_number=q)
return redirect('reports.views.report', lot_number=report.lot_number)
except:
""" No lot # could be found, perform a search """
sqs = SearchQuerySet().auto_query(q)
results = sqs.filter(content=AutoQuery(q))
try:
page = request.GET.get('page', 1)
except PageNotAnInteger:
page = 1
p = Paginator(sqs, 20, request=request)
results_list = p.page(page)
else:
sqs = None
results_list = []
end = time.time()
runtime = end-start
return render_to_response('search/search.html',
{
'results_list': results_list,
'query': q,
'runtime': runtime,
},
context_instance=RequestContext(request))
开发者ID:disflux,项目名称:django-mtr,代码行数:42,代码来源:views.py
示例14: search
def search(request):
if request.method == 'POST':
form = SearchForm(request.POST)
if form.is_valid():
#startPos and endPos are the lat/long for the address passed in via the form (javascript)
startAddress = form.cleaned_data['startAddress']
startLat = float(form.cleaned_data['startLat'])
startLong = float(form.cleaned_data['startLong'])
endAddress = form.cleaned_data['endAddress']
endLat = float(form.cleaned_data['endLat'])
endLong = float(form.cleaned_data['endLong'])
distance = float(form.cleaned_data['distance'])
results = runSearch(startAddress, startLat, startLong, endAddress, endLat, endLong, distance)
query = reduce(operator.or_, (Q(pk=x) for x in results))
results = Trip.objects.filter(query)
return direct_to_template(request, 'search.html', { 'results': results, 'authenticated' : request.user.is_authenticated() })
# handle the typical ajax search request
elif request.method == 'GET':
startAddress = request.GET.get('startAddress' ,'')
startLat = request.GET.get('startLat', '')
startLong = request.GET.get('startLong', '')
endAddress = request.GET.get('endAddress' ,'')
endLat = request.GET.get('endLat' ,'')
endLong = request.GET.get('endLong', '')
distance = request.GET.get('distance', '')
results = runSearch(startAddress, startLat, startLong, endAddress, endLat, endLong, distance)
query = reduce(operator.or_, (Q(pk=x) for x in results))
results = Trip.objects.filter(query)
return HttpResponse(results)
else:
form = SearchForm()
return direct_to_template(request, 'search.html', { 'form' : form } )
开发者ID:JDrosdeck,项目名称:ziptrail.com,代码行数:41,代码来源:views.py
示例15: search
def search(request):
if request.method == "POST":
searchform = SearchForm(request.POST)
if searchform.is_valid():
query = searchform.data.get('query')
query_list = query.lower().split(',')
if len(query_list) > 1:
try:
qs = [list(chain(*[skill.profile_set.all() for skill in Skill.objects.filter(name__contains=tag_clean(qry))])) for qry in query_list]
results = list(set(qs[0]).intersection(*qs))
except Exception, e:
results = None
else:
try:
results = list(chain(Skill.objects.get(name__contains=query_list[0]).profile_set.all()))
except Exception, e:
if e.__class__ == Skill.MultipleObjectsReturned:
results = list(chain(*[skill.profile_set.all() for skill in Skill.objects.filter(name__contains=query_list[0])]))
else:
results = None
searchform = SearchForm({'query':query})
开发者ID:apenwarr,项目名称:hnofficehours,代码行数:21,代码来源:views.py
示例16: get_object
def get_object(self, request):
form = SearchForm(request.GET)
form.is_valid()
self.query = query = form.cleaned_data
t = query.get('type')
self.search_type = _TYPES.get(t)
self.search_query = query.get('q', '')
filters = {}
if t:
filters['type'] = t
if query.get('author'):
filters['author'] = query['author'].id
if query.get('copies'):
filters['copies_count'] = query['copies']
return package_search(self.search_query, user=request.user,
**filters).order_by('-created_at')[:20]
开发者ID:Jnull,项目名称:FlightDeck,代码行数:21,代码来源:feeds.py
示例17: search
def search(self, rdata, user, testing=False):
sqs = SearchQuerySet().result_class(VideoSearchResult) \
.models(Video)
rdata['q'] = rdata['q'] or u' '
q = rdata.get('q')
if q:
sqs = SearchForm.apply_query(q, sqs)
form = SearchForm(rdata, sqs=sqs)
else:
form = SearchForm(rdata)
if form.is_valid():
qs = form.search_qs(sqs)
else:
qs = SearchQuerySet().none()
#result = [item.object for item in qs]
#qs1 = Video.objects.filter(title__contains=rdata['q'])
#for o in qs1:
# if not o in result:
# print o.title
display_views = form.get_display_views()
output = render_page(rdata.get('page', 1), qs, 20, display_views=display_views)
output['sidebar'] = render_to_string('search/_sidebar.html', dict(form=form, rdata=rdata))
if testing:
output['sqs'] = qs
return output
开发者ID:adncentral,项目名称:unisubs,代码行数:32,代码来源:rpc.py
示例18: search
def search(request, page=1):
paged_results = []
count = 0
if "page" in request.GET:
page = request.GET["page"]
if "keyword" in request.GET:
form = SearchForm(request.GET)
if form.is_valid():
query = create_search_query(form.cleaned_data["keyword"])
search_results = Search.objects.filter(text__search=query, status=1).order_by("update_date").all()
if search_results:
paginator = Paginator(search_results, settings.ITEMS_PER_PAGE)
try:
paged_results = paginator.page(page)
count = paginator.count
except PageNotAnInteger:
raise Http404
except EmptyPage:
raise Http404
else:
results = []
target_models = get_search_target_models()
for target in target_models:
model_name = target().__class__.__name__
target_results = target.objects.filter(
pk__in=[item.model_pk for item in paged_results if item.model == model_name]
)
for item in target_results:
results.append(item)
results.sort(key=lambda x: x.update_date, reverse=True)
paged_results.object_list = results
else:
form = SearchForm()
return render_to_response(
"search/index.html",
{"form": form, "count": count, "results": paged_results},
context_instance=RequestContext(request),
)
开发者ID:wanshot,项目名称:trdist,代码行数:39,代码来源:views.py
示例19: home
def home(request):
"""
This function is called for display the Home page
@param request : Contains the query parameters
This function just accepts the GET method
"""
if request.method == 'GET': # For the GET method
form = SearchForm() # Nous creons un formulaire vide
elif request.method == 'POST':
# create a form instance and populate it with data from the request:
formulaire = SearchForm(request.POST)
# check whether it's valid:
if formulaire.is_valid():
day_month = request.POST.get('day_month')
day_day = request.POST.get('day_day')
day_year = request.POST.get('day_year')
hour_hour = request.POST.get('hour_hour')
hour_minute = request.POST.get('hour_minute')
station = request.POST.get('station')
hour = "%s/%s/%s %s:%s" % (day_year, day_month, day_day, hour_hour, hour_minute)
timestamp = date2Timestamp(hour)
prev = previsions(timestamp, station)
return Response(locals(), template_name='home.html') # Return the response
开发者ID:afaraut,项目名称:SmartCityVeloV,代码行数:23,代码来源:views.py
示例20: search_with_sphinx
def search_with_sphinx(request, template=None):
"""Sphinx-specific search view"""
# Time ES and Sphinx separate. See bug 723930.
# TODO: Remove this once Sphinx is gone.
start = time.time()
# JSON-specific variables
is_json = (request.GET.get('format') == 'json')
callback = request.GET.get('callback', '').strip()
mimetype = 'application/x-javascript' if callback else 'application/json'
if waffle.flag_is_active(request, 'elasticsearch'):
engine = 'elastic'
else:
engine = 'sphinx'
# Search "Expires" header format
expires_fmt = '%A, %d %B %Y %H:%M:%S GMT'
# Check callback is valid
if is_json and callback and not jsonp_is_valid(callback):
return HttpResponse(
json.dumps({'error': _('Invalid callback function.')}),
mimetype=mimetype, status=400)
language = locale_or_default(request.GET.get('language', request.locale))
r = request.GET.copy()
a = request.GET.get('a', '0')
# Search default values
try:
category = map(int, r.getlist('category')) or \
settings.SEARCH_DEFAULT_CATEGORIES
except ValueError:
category = settings.SEARCH_DEFAULT_CATEGORIES
r.setlist('category', category)
# Basic form
if a == '0':
r['w'] = r.get('w', constants.WHERE_BASIC)
# Advanced form
if a == '2':
r['language'] = language
r['a'] = '1'
# TODO: Rewrite so SearchForm is unbound initially and we can use `initial`
# on the form fields.
if 'include_archived' not in r:
r['include_archived'] = False
search_form = SearchForm(r)
if not search_form.is_valid() or a == '2':
if is_json:
return HttpResponse(
json.dumps({'error': _('Invalid search data.')}),
mimetype=mimetype,
status=400)
t = template if request.MOBILE else 'search/form.html'
search_ = jingo.render(request, t,
{'advanced': a, 'request': request,
'search_form': search_form})
search_['Cache-Control'] = 'max-age=%s' % \
(settings.SEARCH_CACHE_PERIOD * 60)
search_['Expires'] = (datetime.utcnow() +
timedelta(
minutes=settings.SEARCH_CACHE_PERIOD)) \
.strftime(expires_fmt)
return search_
cleaned = search_form.cleaned_data
page = max(smart_int(request.GET.get('page')), 1)
offset = (page - 1) * settings.SEARCH_RESULTS_PER_PAGE
# get language name for display in template
lang = language.lower()
if settings.LANGUAGES.get(lang):
lang_name = settings.LANGUAGES[lang]
else:
lang_name = ''
wiki_s = wiki_searcher(request)
question_s = question_searcher(request)
discussion_s = discussion_searcher(request)
documents = []
# wiki filters
# Category filter
if cleaned['category']:
wiki_s = wiki_s.filter(category__in=cleaned['category'])
# Locale filter
wiki_s = wiki_s.filter(locale=language)
# Product filter
products = cleaned['product']
#.........这里部分代码省略.........
开发者ID:ccarruitero,项目名称:kitsune,代码行数:101,代码来源:views.py
注:本文中的search.forms.SearchForm类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论