def tour_page(request, slug): '''Página única de cada tour.''' tour = get_object_or_404(Tour, slug=slug) references = tour.references.all() query = MlSearchQuerySet().filter(tour=tour.id) photos = query.filter(is_image=1) videos = query.filter(is_video=1) # photos = tour.images.filter(tourposition__tour=tour).select_related('size', 'sublocation', 'city', 'state', 'country').order_by('tourposition') # videos = tour.videos.select_related('size', 'sublocation', 'city', 'state', 'country') try: thumb = photos.values_list('thumb_filepath', flat=True)[0] except: thumb = '' # Extrair metadados das imagens. authors, taxa, sizes, sublocations, cities, states, countries, tags = extract_set(photos, videos) # Atualiza contador de visualizações. stats = tour.stats pageviews = stats.pageviews variables = RequestContext(request, { 'tour': tour, 'photos': photos, 'videos': videos, 'thumb': thumb, 'taxa': taxa, 'tags': tags, 'authors': authors, 'references': references, 'pageviews': pageviews, }) return render_to_response('tour_page.html', variables)
def tour_page(request, slug): '''Página única de cada tour.''' tour = get_object_or_404(Tour, slug=slug) references = tour.references.all() query = MlSearchQuerySet().filter(tour=tour.id) photos = query.filter(is_image=1) videos = query.filter(is_video=1) # photos = tour.images.filter(tourposition__tour=tour).select_related('size', 'sublocation', 'city', 'state', 'country').order_by('tourposition') # videos = tour.videos.select_related('size', 'sublocation', 'city', 'state', 'country') try: thumb = photos.values_list('thumb_filepath', flat=True)[0] except: thumb = '' # Extrair metadados das imagens. authors, taxa, sizes, sublocations, cities, states, countries, tags = extract_set( photos, videos) # Atualiza contador de visualizações. stats = tour.stats pageviews = stats.pageviews variables = RequestContext( request, { 'tour': tour, 'photos': photos, 'videos': videos, 'thumb': thumb, 'taxa': taxa, 'tags': tags, 'authors': authors, 'references': references, 'pageviews': pageviews, }) return render_to_response('tour_page.html', variables)
def ajax_autocomplete(request): limit = 5 # max results in number max_str = 30 # max result text size, in chars search_query = strip_accents(request.GET.get( 'q', '')) # get without accents query query = MlSearchQuerySet().autocomplete(content_auto=search_query) results = query.values('title', 'rendered', 'thumb', 'url') suffix = query.get_language_suffix( ) # get language suffix to 'languaged' fields final_results = [] # array of results titles = [] for d in results: text = d['rendered%s' % suffix] title = d['title%s' % suffix] thumb = d['thumb'] url = d['url'] if limit <= 0: break # check if there is already some result with same title if title not in titles: limit -= 1 titles.append(title) label = '' desc = title if text: # if there is a text field, otherwise search is not cached for t in text.split("\n"): if search_query.lower() in t.lower(): ts = t.split( ":" ) # : separates label from real text, in the rendered field label = ts[0] desc = ":".join(ts[1:]) if len(t) > max_str: # cut str if it's too long i = desc.lower().find(search_query.lower()) start = max(0, i - max_str / 2) end = min(len(desc), i + max_str / 2) desc = '...' + desc[start:end] + '...' break final_results.append({ 'title': title, 'desc': desc, 'label': label, 'thumb': thumb, 'url': url }) return HttpResponse(json.dumps(final_results), content_type='application/json')
def ajax_autocomplete(request): limit = 5 # max results in number max_str = 30 # max result text size, in chars search_query = strip_accents(request.GET.get('q', '')) # get without accents query query = MlSearchQuerySet().autocomplete(content_auto=search_query) results = query.values('title', 'rendered', 'thumb', 'url') suffix = query.get_language_suffix() # get language suffix to 'languaged' fields final_results = [] # array of results titles = [] for d in results: text = d['rendered%s' % suffix] title = d['title%s' % suffix] thumb = d['thumb'] url = d['url'] if limit <= 0: break # check if there is already some result with same title if title not in titles: limit -= 1 titles.append(title) label = '' desc = title if text: # if there is a text field, otherwise search is not cached for t in text.split("\n"): if search_query.lower() in t.lower(): ts = t.split(":") # : separates label from real text, in the rendered field label = ts[0] desc = ":".join(ts[1:]) if len(t) > max_str: # cut str if it's too long i = desc.lower().find(search_query.lower()) start = max(0, i - max_str / 2) end = min(len(desc), i + max_str / 2) desc = '...' + desc[start:end] + '...' break final_results.append({'title': title, 'desc': desc, 'label': label, 'thumb': thumb, 'url': url}) return HttpResponse(json.dumps(final_results), content_type='application/json')
def search_page(request): # Define formulários. form = SearchForm() n_form = DisplayForm(initial={ 'n': 16, 'order': 'random', 'highlight': False }) # Refinamentos. queries = { u'query': '', u'author': [], u'tag': [], u'size': [], u'taxon': [], u'sublocation': [], u'city': [], u'state': [], u'country': [], u'type': [], } # Define variáveis principais. image_list = MlSearchQuerySet().filter(is_image=True) # Image.objects.filter(is_public=True) video_list = MlSearchQuerySet().filter(is_video=True) # Video.objects.filter(is_public=True) show_results = False full_results = True # Verifica se qualquer um dos campos foi passado no request. if catch_get(queries.keys(), request.GET): # Sinal para mostrar resultados no template. show_results = True # Define formulário de controle e variáveis. n_form, n_page, orderby, order, highlight = control_form(request) # Cria querysets somente com imagens públicas para serem filtrados por # cada metadado presente no request. if 'type' in request.GET: type = request.GET['type'] if type == 'photo': video_list = video_list.none() elif type == 'video': image_list = image_list.none() # Query if 'query' in request.GET: # Limpa espaços extras. query = request.GET['query'].strip() if query: # Ajusta busca textual para locale do usuário, 'portuguese' padrão. image_list = image_list.auto_query(query) video_list = video_list.auto_query(query) # Popula formulário de busca com o query. form = SearchForm({'query': query}) # Passa valor para as queries. queries['query'] = query full_results = False # Author if 'author' in request.GET: authors = request.GET['author'].split(',') queries['author'] = Author.objects.filter(slug__in=authors) ids = queries['author'].values_list('id', flat=True) for author in ids: image_list = image_list.filter(author=author) video_list = video_list.filter(author=author) full_results = False # Tag if 'tag' in request.GET: tags = request.GET['tag'].split(',') queries['tag'] = Tag.objects.filter(slug__in=tags) ids = queries['tag'].values_list('id', flat=True) for tag in ids: image_list = image_list.filter(tag=tag) video_list = video_list.filter(tag=tag) full_results = False # Size if 'size' in request.GET: size_id = request.GET['size'] queries['size'] = Size.objects.filter(id=size_id) image_list = image_list.filter(size=size_id) video_list = video_list.filter(size=size_id) full_results = False # Taxon if 'taxon' in request.GET: taxa = request.GET['taxon'].split(',') queries['taxon'] = Taxon.objects.filter(slug__in=taxa) # Precisa listar descendentes também, logo use o recurse: qim = [] qvid = [] for taxon_slug in taxa: taxon = Taxon.objects.get(slug=taxon_slug) # for im in taxon.images.all(): # qim.append(Q(**{'id':im.id})) # for vid in taxon.videos.all(): # qvid.append(Q(**{'id':vid.id})) qim.append(Q(**{'taxon': taxon.id})) qvid.append(Q(**{'taxon': taxon.id})) children = taxon.get_descendants() for child in children: qim.append(Q(**{'taxon': child.id})) qvid.append(Q(**{'taxon': child.id})) # for im in child.images.all(): # qim.append(Q(**{'id': im.id})) # for vid in child.videos.all(): # qvid.append(Q(**{'id': vid.id})) if qim: image_list = image_list.filter(reduce(operator.or_, qim)) else: image_list = image_list.none() if qvid: video_list = video_list.filter(reduce(operator.or_, qvid)) else: video_list = video_list.none() full_results = False # Sublocation if 'sublocation' in request.GET: sublocations = request.GET['sublocation'].split(',') queries['sublocation'] = Sublocation.objects.filter(slug__in=sublocations) ids = queries['sublocation'].values_list('id', flat=True) for sublocation in ids: image_list = image_list.filter(sublocation__slug=sublocation) video_list = video_list.filter(sublocation__slug=sublocation) full_results = False # City if 'city' in request.GET: cities = request.GET['city'].split(',') queries['city'] = City.objects.filter(slug__in=cities) ids = queries['city'].values_list('id', flat=True) for city in ids: image_list = image_list.filter(city=city) video_list = video_list.filter(city=city) full_results = False # State if 'state' in request.GET: states = request.GET['state'].split(',') queries['state'] = State.objects.filter(slug__in=states) ids = queries['state'].values_list('id', flat=True) for state in ids: image_list = image_list.filter(state=state) video_list = video_list.filter(state=state) full_results = False # Country if 'country' in request.GET: countries = request.GET['country'].split(',') queries['country'] = Country.objects.filter(slug__in=countries) ids = queries['country'].values_list('id', flat=True) for country in ids: image_list = image_list.filter(country=country) video_list = video_list.filter(country=country) full_results = False # Restringe aos destaques. if highlight: image_list = image_list.filter(highlight=1) video_list = video_list.filter(highlight=1) # full_results = False # # Substitui 'random' por '?' if orderby in ('?', 'random', 'id'): orderby = 'id' if order == 'desc': orderby = '-' + orderby # # # Ordena por request.POST['orderby']. image_list = image_list.order_by(orderby) video_list = video_list.order_by(orderby) # Forçar int para paginator. n_page = int(n_page) else: # Popula formulário de busca com o query. form = SearchForm() # Passa valor para as queries. queries['query'] = '' n_page = 20 show_results = True # Retorna lista paginada. images = get_paginated(request, image_list, n_page) videos = get_paginated(request, video_list, n_page) # Gera keywords. #XXX Usar essa lista para processar os querysets acima? keylist = [] for k, v in request.GET.iteritems(): keylist.append(v) keylist = [item for item in keylist if item] keywords = ','.join(keylist) # Extrai metadados das imagens. data, queries, urls = show_info(image_list, video_list, queries, full_results) variables = RequestContext(request, { 'form': form, 'images': images, 'videos': videos, 'image_list': image_list, 'video_list': video_list, 'show_results': show_results, 'queries': queries, 'data': data, 'urls': urls, 'n_form': n_form, 'keywords': keywords, }) return render_to_response('buscar.html', variables)
def meta_page(request, model_name, field, slug): '''Página de um metadado. Mostra galeria com todas as imagens que o possuem. ''' # Formulário para controle de ordenação. n_form = DisplayForm(initial={ 'n': 16, 'order': 'random', 'highlight': False, }) # Define formulário de controle e variáveis. n_form, n_page, orderby, order, highlight = control_form(request) # Queries guardam variáveis do request para o refinador. queries = { u'query': '', u'author': [], u'tag': [], u'size': [], u'taxon': [], u'sublocation': [], u'city': [], u'state': [], u'country': [], u'type': [], } #XXX Serve para identificar o field na meta_page. Mas precisa ser # um queryset para rolar o values_list do show_info no extra_tags. # Se possível otimizar isso. qmodels = model_name.objects.filter(slug__in=[slug]) queries[field] = qmodels # Pega objeto. model = get_object_or_404(model_name, slug=slug) # Constrói argumentos. filter_args = {field: model.id, 'is_public': True} if field == 'taxon': q = [Q(**filter_args), ] q = recurse(model, q) image_list = MlSearchQuerySet().filter(is_image=True).filter(reduce(operator.or_, q)) # .order_by(orderby) video_list = MlSearchQuerySet().filter(is_video=True).filter(reduce(operator.or_, q)) # .order_by(orderby) #XXX Retirei o .distinct() destes queries. Conferir... else: image_list = MlSearchQuerySet().filter(is_image=True).filter(**filter_args) # .order_by(orderby) video_list = MlSearchQuerySet().filter(is_video=True).filter(**filter_args) # .order_by(orderby) # Restringe aos destaques. if highlight: image_list = image_list.filter(highlight=1) video_list = video_list.filter(highlight=1) # Reverte a ordem se necessário. # if order == 'desc': # image_list = image_list.reverse() # video_list = video_list.reverse() # Forçar int para paginator. n_page = int(n_page) # Cria paginação. images = get_paginated(request, image_list, n_page) videos = get_paginated(request, video_list, n_page) # Extrai metadados das imagens. data, queries, urls = show_info(image_list, video_list, queries) variables = RequestContext(request, { 'images': images, 'videos': videos, 'image_list': image_list, 'video_list': video_list, 'meta': model, 'queries': queries, 'data': data, 'urls': urls, 'field': field, 'queries': queries, 'n_form': n_form, }) return render_to_response('meta_page.html', variables)
def search_page(request): # Define formulários. form = SearchForm() n_form = DisplayForm(initial={ 'n': 16, 'order': 'random', 'highlight': True }) # Refinamentos. queries = { u'query': '', u'author': [], u'tag': [], u'size': [], u'taxon': [], u'sublocation': [], u'city': [], u'state': [], u'country': [], u'type': [], } # Define variáveis principais. image_list = MlSearchQuerySet().filter( is_image=True) #Image.objects.filter(is_public=True) video_list = MlSearchQuerySet().filter( is_video=True) #Video.objects.filter(is_public=True) show_results = False full_results = True # Verifica se qualquer um dos campos foi passado no request. if catch_get(queries.keys(), request.GET): # Sinal para mostrar resultados no template. show_results = True # Define formulário de controle e variáveis. n_form, n_page, orderby, order, highlight = control_form(request) # Cria querysets somente com imagens públicas para serem filtrados por # cada metadado presente no request. if 'type' in request.GET: type = request.GET['type'] if type == 'photo': video_list = video_list.none() elif type == 'video': image_list = image_list.none() # Query if 'query' in request.GET: # Limpa espaços extras. query = request.GET['query'].strip() if query: # Ajusta busca textual para locale do usuário, 'portuguese' padrão. image_list = image_list.auto_query(query) video_list = video_list.auto_query(query) # Popula formulário de busca com o query. form = SearchForm({'query': query}) # Passa valor para as queries. queries['query'] = query full_results = False # Author if 'author' in request.GET: authors = request.GET['author'].split(',') queries['author'] = Author.objects.filter(slug__in=authors) ids = queries['author'].values_list('id', flat=True) for author in ids: image_list = image_list.filter(author=author) video_list = video_list.filter(author=author) full_results = False # Tag if 'tag' in request.GET: tags = request.GET['tag'].split(',') queries['tag'] = Tag.objects.filter(slug__in=tags) ids = queries['tag'].values_list('id', flat=True) for tag in ids: image_list = image_list.filter(tag=tag) video_list = video_list.filter(tag=tag) full_results = False # Size if 'size' in request.GET: size_id = request.GET['size'] queries['size'] = Size.objects.filter(id=size_id) image_list = image_list.filter(size=size_id) video_list = video_list.filter(size=size_id) full_results = False # Taxon if 'taxon' in request.GET: taxa = request.GET['taxon'].split(',') queries['taxon'] = Taxon.objects.filter(slug__in=taxa) # Precisa listar descendentes também, logo use o recurse: qim = [] qvid = [] for taxon_slug in taxa: taxon = Taxon.objects.get(slug=taxon_slug) # for im in taxon.images.all(): # qim.append(Q(**{'id':im.id})) # for vid in taxon.videos.all(): # qvid.append(Q(**{'id':vid.id})) qim.append(Q(**{'taxon': taxon.id})) qvid.append(Q(**{'taxon': taxon.id})) children = taxon.get_descendants() for child in children: qim.append(Q(**{'taxon': child.id})) qvid.append(Q(**{'taxon': child.id})) # for im in child.images.all(): # qim.append(Q(**{'id': im.id})) # for vid in child.videos.all(): # qvid.append(Q(**{'id': vid.id})) if qim: image_list = image_list.filter(reduce(operator.or_, qim)) else: image_list = image_list.none() if qvid: video_list = video_list.filter(reduce(operator.or_, qvid)) else: video_list = video_list.none() full_results = False # Sublocation if 'sublocation' in request.GET: sublocations = request.GET['sublocation'].split(',') queries['sublocation'] = Sublocation.objects.filter( slug__in=sublocations) ids = queries['sublocation'].values_list('id', flat=True) for sublocation in ids: image_list = image_list.filter(sublocation__slug=sublocation) video_list = video_list.filter(sublocation__slug=sublocation) full_results = False # City if 'city' in request.GET: cities = request.GET['city'].split(',') queries['city'] = City.objects.filter(slug__in=cities) ids = queries['city'].values_list('id', flat=True) for city in ids: image_list = image_list.filter(city=city) video_list = video_list.filter(city=city) full_results = False # State if 'state' in request.GET: states = request.GET['state'].split(',') queries['state'] = State.objects.filter(slug__in=states) ids = queries['state'].values_list('id', flat=True) for state in ids: image_list = image_list.filter(state=state) video_list = video_list.filter(state=state) full_results = False # Country if 'country' in request.GET: countries = request.GET['country'].split(',') queries['country'] = Country.objects.filter(slug__in=countries) ids = queries['country'].values_list('id', flat=True) for country in ids: image_list = image_list.filter(country=country) video_list = video_list.filter(country=country) full_results = False # Restringe aos destaques. if highlight: image_list = image_list.filter(highlight=1) video_list = video_list.filter(highlight=1) # full_results = False # # Substitui 'random' por '?' if orderby in ('?', 'random', 'id'): orderby = 'id' if order == 'desc': orderby = '-' + orderby # # # Ordena por request.POST['orderby']. image_list = image_list.order_by(orderby) video_list = video_list.order_by(orderby) # Forçar int para paginator. n_page = int(n_page) else: # Popula formulário de busca com o query. form = SearchForm() # Passa valor para as queries. queries['query'] = '' n_page = 20 show_results = True # Retorna lista paginada. images = get_paginated(request, image_list, n_page) videos = get_paginated(request, video_list, n_page) # Gera keywords. #XXX Usar essa lista para processar os querysets acima? keylist = [] for k, v in request.GET.iteritems(): keylist.append(v) keylist = [item for item in keylist if item] keywords = ','.join(keylist) # Extrai metadados das imagens. data, queries, urls = show_info(image_list, video_list, queries, full_results) variables = RequestContext( request, { 'form': form, 'images': images, 'videos': videos, 'image_list': image_list, 'video_list': video_list, 'show_results': show_results, 'queries': queries, 'data': data, 'urls': urls, 'n_form': n_form, 'keywords': keywords, }) return render_to_response('buscar.html', variables)
def meta_page(request, model_name, field, slug): '''Página de um metadado. Mostra galeria com todas as imagens que o possuem. ''' # Formulário para controle de ordenação. n_form = DisplayForm(initial={ 'n': 16, 'order': 'random', 'highlight': True, }) # Define formulário de controle e variáveis. n_form, n_page, orderby, order, highlight = control_form(request) # Queries guardam variáveis do request para o refinador. queries = { u'query': '', u'author': [], u'tag': [], u'size': [], u'taxon': [], u'sublocation': [], u'city': [], u'state': [], u'country': [], u'type': [], } #XXX Serve para identificar o field na meta_page. Mas precisa ser # um queryset para rolar o values_list do show_info no extra_tags. # Se possível otimizar isso. qmodels = model_name.objects.filter(slug__in=[slug]) queries[field] = qmodels # Pega objeto. model = get_object_or_404(model_name, slug=slug) # Constrói argumentos. filter_args = {field: model.id, 'is_public': True} if field == 'taxon': q = [ Q(**filter_args), ] q = recurse(model, q) image_list = MlSearchQuerySet().filter(is_image=True).filter( reduce(operator.or_, q)) #.order_by(orderby) video_list = MlSearchQuerySet().filter(is_video=True).filter( reduce(operator.or_, q)) #.order_by(orderby) #XXX Retirei o .distinct() destes queries. Conferir... else: image_list = MlSearchQuerySet().filter( is_image=True).filter(**filter_args) #.order_by(orderby) video_list = MlSearchQuerySet().filter( is_video=True).filter(**filter_args) #.order_by(orderby) # Restringe aos destaques. if highlight: image_list = image_list.filter(highlight=1) video_list = video_list.filter(highlight=1) # Reverte a ordem se necessário. # if order == 'desc': # image_list = image_list.reverse() # video_list = video_list.reverse() # Forçar int para paginator. n_page = int(n_page) # Cria paginação. images = get_paginated(request, image_list, n_page) videos = get_paginated(request, video_list, n_page) # Extrai metadados das imagens. data, queries, urls = show_info(image_list, video_list, queries) variables = RequestContext( request, { 'images': images, 'videos': videos, 'image_list': image_list, 'video_list': video_list, 'meta': model, 'queries': queries, 'data': data, 'urls': urls, 'field': field, 'queries': queries, 'n_form': n_form, }) return render_to_response('meta_page.html', variables)