本文整理汇总了Python中search.forms.SearchForm类的典型用法代码示例。如果您正苦于以下问题:Python SearchForm类的具体用法?Python SearchForm怎么用?Python SearchForm使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了SearchForm类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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))
示例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})
示例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)
示例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)))
示例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
示例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))
示例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)
示例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)
示例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))
示例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])
示例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())
示例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);
示例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))
示例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 } )
示例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})