def result_summary_info(request,object_id): """Present a result summary""" object = get_object_or_404(Results.ResultSummaryList, pk=object_id) protocolfields={} for (fieldname, text, cond) in [("version_intolerant", "Version Intolerant", Results.ResultCondition.RESULTC_VERSION_INTOLERANT), ("extension_intolerant","Extension Intolerant", Results.ResultCondition.RESULTC_EXTENSION_INTOLERANT), ("extension_and_version_intolerant","Extension and Version Intolerant", Results.ResultCondition.RESULTC_VERANDEXT_INTOLERANT), ("extension_or_version_intolerant","Extension or Version Intolerant", Results.ResultCondition.RESULTC_VEROREXT_INTOLERANT), ("bad_version","Require Bad Version", Results.ResultCondition.RESULTC_BADVERSION), ("bad_check","No Version check", Results.ResultCondition.RESULTC_NOVERSION), ]: cond_item = object.conditions.get(condition = cond) for (ver) in [(3,0),(3,1),(3,2),(3,3),(3,4),(3,11),(4,1),(0,3),(0,4)]: if ver == (3,0): title = "SSL v3" elif ver[0] == 0: title = "Summary TLS %d.x" %(ver[1]-2,) else: title = "TLS %d.%d" %(ver[0]-2, (ver[1]-1 if ver[0]==3 else ver[1])) Q = cond_item.resultentryprotocol_set.filter(version_tested_major=ver[0],version_tested_minor=ver[1]) protocolfields.setdefault(str(ver),{"title":title, "values":{}})["values"][fieldname]={"header":text, "count":Q.count()} summary_fields = [] for (fieldname, text, cond) in [("renego", "Renego Patched", Results.ResultCondition.RESULTC_RENEGO), ("renego_noncompliant", "Renego Patched but non-compliant", Results.ResultCondition.RESULTC_RENEGONONCOMPLIANT), ("renego_unpatched", "Not Renego Patched", Results.ResultCondition.RESULTC_NONRENEGO), ("renego_unstable", "Renego Patched, but unstable", Results.ResultCondition.RESULTC_RENEGOUNSTABLE), ]: cond_item = object.conditions.get(condition = cond) Q = cond_item.resultentry_set.all() summary_fields.append({"header":text, "count":Q.count()}) return render_to_response("summary.html", { "object":object, "protocolfields":protocolfields, "summary_fields":summary_fields, "debug_output":[x for x in connection.queries], })
def get_queryset(self): return super(ActiveManager, self).get_queryset().all().exclude(Q(hidden=True) | Q(tags__isnull=True))
def board_article_list(request, board_name=None, page_num=1): if board_name is None: raise PermissionDenied() try: board = Board.objects.get(name=board_name) except: raise Http404() search_type = request.GET.get('search_type', '') query = request.GET.get('query', '') is_search = True if search_type == 'title': articles = Article.objects.filter( board=board, deleted=False, is_important=False, title__contains=query).order_by('-id') elif search_type == 'content': articles = Article.objects.filter( board=board, deleted=False, is_important=False, content__contains=query).order_by('-id') elif search_type == 'title.content': q = operator.and_( operator.or_(Q(title__contains=query), Q(content__contains=query)), Q(board=board, deleted=False, is_important=False)) articles = Article.objects.filter(q).order_by('-id') elif search_type == 'username' and not board.is_anonymous: articles = Article.objects.filter(board=board, deleted=False, is_important=False, user__username=query).order_by('-id') elif search_type == 'name' and not board.is_anonymous: articles = Article.objects.filter( board=board, deleted=False, is_important=False, writer_name__contains=query).order_by('-id') else: articles = Article.objects.filter(board=board, deleted=False, is_important=False).order_by('-id') is_search = False count_per_page = board.article_per_page total_page_num = max((articles.count() - 1) / count_per_page + 1, 1) page_num = int(page_num) if page_num < 1 or page_num > total_page_num: raise Http404() start = (page_num - 1) * count_per_page end = page_num * count_per_page articles = articles[start:end] page_nums = get_page_nums(total_page_num, 5, page_num) important_articles = Article.objects.filter( board=board, deleted=False, is_important=True).order_by('-id') article_count = articles.count() + important_articles.count() return render_to_response( 'board/article_list.html', RequestContext( request, { 'board': board, 'articles': articles, 'page_num': page_num, 'total_page_num': total_page_num, 'page_nums': page_nums, 'get_parameters': request.GET.urlencode(), 'get_dict': request.GET, 'article_count': article_count, 'is_search': is_search, 'important_articles': important_articles }))
def get_event_summary(request): """ API to return summary of ongoing events organized by the user :param request: organizer id :return: data object returning the event details like sold tickets, revenue etc. """ token = get_authorization_header(request).split()[1] payload = jwt.decode(token, SECRET_KEY) user_id = payload['user_id'] search_text = request.GET.get("search", None) event_status_filter = request.GET.get('event_status', EVENT_STATUS['all']) today = date.today() queryset = Event.objects.filter(event_created_by=user_id).order_by('id') queryset.filter(date__lt=str(today)).update(is_active=False) total_revenue, revenue_cancelled_events, revenue_completed_events, revenue_ongoing_events = 0, 0, 0, 0 if event_status_filter.lower() == EVENT_STATUS['completed']: queryset = queryset.filter(is_active=False, is_cancelled=False) elif event_status_filter.lower() == EVENT_STATUS['cancelled']: queryset = queryset.filter(is_active=False, is_cancelled=True) elif event_status_filter.lower() == EVENT_STATUS['default']: queryset = queryset.filter(date__gte=str(today), is_active=True) if search_text: queryset = queryset.filter( Q(location__icontains=search_text) | Q(name__icontains=search_text)) cancelled_events, completed_events, ongoing_events, total_events = 0, 0, 0, queryset.count( ) data = {'event_list': []} event_name_list = [] event_revenue_list = [] event_remaining_tickets = [] event_sold_tickets = [] try: for event in queryset: if event.subscription_fee == 0: revenue = 0 else: total_amount = Subscription.objects.filter( event=event.id, is_active=True).aggregate(Sum("amount")) if total_amount["amount__sum"]: revenue = total_amount["amount__sum"] else: revenue = 0 if event.is_cancelled: revenue = 0 total_revenue += revenue event_status = EVENT_STATUS['default'] if event.is_cancelled: event_status = EVENT_STATUS['cancelled'] revenue_cancelled_events += revenue cancelled_events += 1 if not event.is_active and not event.is_cancelled: event_status = EVENT_STATUS['completed'] revenue_completed_events += revenue completed_events += 1 if event_status == EVENT_STATUS['default']: revenue_ongoing_events += revenue ongoing_events += 1 data['event_list'].append({ 'key': event.id, 'name': event.name, 'total_tickets': event.no_of_tickets, 'sold_tickets': event.sold_tickets, 'revenue': revenue, 'location': event.location, 'status': event_status }) event_name_list.append(event.name) event_revenue_list.append(revenue) event_remaining_tickets.append(event.no_of_tickets - event.sold_tickets) event_sold_tickets.append(event.sold_tickets) data['total_revenue'] = total_revenue data['total_events'] = total_events data['ongoing_events'] = ongoing_events data['completed_events'] = completed_events data['cancelled_events'] = cancelled_events data['revenue_ongoing_events'] = revenue_ongoing_events data['revenue_completed_events'] = revenue_completed_events data['revenue_cancelled_events'] = revenue_cancelled_events data['ticket_graph_object'] = { 'name_list': event_name_list, 'revenue_list': event_revenue_list, 'remaining_tickets': event_remaining_tickets, 'sold_tickets': event_sold_tickets } monthly_data = get_month_wise_data(queryset) data['monthly_event_count'] = monthly_data['events'] data['monthly_revenue'] = monthly_data['revenue'] except Exception as err: logger.log_error(str(err)) return api_error_response(message="Some internal error occur", status=500) logger.log_info( f"Analytics successfully sent for events of organizer with user_id {user_id}" ) return api_success_response(message="Summary of all events", data=data, status=200)
def createQ(token): """Creates the Q() object""" meta = getattr(token, 'meta', None) query = getattr(token, 'query', '') wildcards = None if isinstance(query, basestring): # Unicode -> Quoted string search = query else: # List -> No quoted string (possible wildcards) if len(query) == 1: search = query[0] elif len(query) == 3: wildcards = 'BOTH' search = query[1] elif len(query) == 2: if query[0] == '*': wildcards = 'START' search = query[1] else: wildcards = 'END' search = query[0] # Ignore connective words (of, a, an...) and STOP_WORDS if (len(search) < 3 and not search.isdigit()) or \ search in STOP_WORDS: return Q() if not meta: return Q(content__icontains=search) | \ Q(excerpt__icontains=search) | \ Q(title__icontains=search) if meta == 'Objecttype': if wildcards == 'BOTH': return Q(objecttypes__title__icontains=search) | \ Q(objecttypes__slug__icontains=search) elif wildcards == 'START': return Q(objecttypes__title__iendswith=search) | \ Q(objecttypes__slug__iendswith=search) elif wildcards == 'END': return Q(objecttypes__title__istartswith=search) | \ Q(objecttypes__slug__istartswith=search) else: return Q(objecttypes__title__iexact=search) | \ Q(objecttypes__slug__iexact=search) elif meta == 'author': if wildcards == 'BOTH': return Q(authors__username__icontains=search) elif wildcards == 'START': return Q(authors__username__iendswith=search) elif wildcards == 'END': return Q(authors__username__istartswith=search) else: return Q(authors__username__iexact=search) elif meta == 'tag': # TODO: tags ignore wildcards return Q(tags__icontains=search)
def child_of_q(self, other): return self.descendant_of_q(other) & Q(depth=other.depth + 1)
def page_q(self, other): return Q(id=other.id)
def live_q(self): return Q(live=True)
def get_queryset(self): """ Get a User queryset for SODARUserAutocompleteWidget. Optional values in self.forwarded: - "project": project UUID - "scope": string for expected scope (all/project/project_exclude) - "exclude": list of explicit User.sodar_uuid to exclude from queryset """ current_user = self.request.user project_uuid = self.forwarded.get('project', None) exclude_uuids = self.forwarded.get('exclude', None) scope = self.forwarded.get('scope', 'all') # If project UUID is given, only show users that are in the project if scope in ['project', 'project_exclude'] and project_uuid not in [ '', None, ]: project = Project.objects.filter(sodar_uuid=project_uuid).first() # If user has no permission for the project, return None if not self.request.user.has_perm('projectroles.view_project', project): return User.objects.none() project_users = [a.user.pk for a in project.get_all_roles()] if scope == 'project': # Limit choices to current project users qs = User.objects.filter(pk__in=project_users) elif scope == 'project_exclude': # Exclude project users qs = User.objects.exclude(pk__in=project_users) # Else include all users else: qs = User.objects.all() # Exclude users in the system group unless local users are allowed allow_local = getattr(settings, 'PROJECTROLES_ALLOW_LOCAL_USERS', False) if not allow_local and not current_user.is_superuser: qs = qs.exclude( groups__name=SODAR_CONSTANTS['SYSTEM_USER_GROUP']).exclude( groups__isnull=True) # Exclude UUIDs explicitly given if exclude_uuids: qs = qs.exclude(sodar_uuid__in=exclude_uuids) # Finally, filter by query if self.q: qs = qs.filter( Q(username__icontains=self.q) | Q(first_name__icontains=self.q) | Q(last_name__icontains=self.q) | Q(name__icontains=self.q) | Q(email__icontains=self.q)) return qs.order_by('name')
def members_by_neighborhood(self, hood, active_only=True): if active_only: return Member.objects.filter(neighborhood=hood).filter(memberships__isnull=False).filter(Q(memberships__end_date__isnull=True) | Q(memberships__end_date__gt=timezone.now().date())).distinct() else: return Member.objects.filter(neighborhood=hood)
def receive(request, key, txid, network): """Handle the receiving of a kudos (the POST). Returns: TemplateResponse: the UI with the kudos confirmed """ these_kudos_transfers = KudosTransfer.objects.filter(web3_type='v3', txid=txid, network=network) kudos_transfers = these_kudos_transfers.filter( Q(metadata__reference_hash_for_receipient=key) | Q(metadata__reference_hash_for_funder=key)) kudos_transfer = kudos_transfers.first() if not kudos_transfer: raise Http404 is_authed = kudos_transfer.trust_url or request.user.username.replace( '@', '').lower() in [ kudos_transfer.username.replace('@', '').lower(), kudos_transfer.from_username.replace('@', '').lower() ] not_mined_yet = get_web3(kudos_transfer.network).eth.getBalance( Web3.toChecksumAddress(kudos_transfer.metadata['address'])) == 0 did_fail = False if not_mined_yet: kudos_transfer.update_tx_status() did_fail = kudos_transfer.tx_status in [ 'dropped', 'unknown', 'na', 'error' ] if not kudos_transfer.trust_url: if not request.user.is_authenticated or request.user.is_authenticated and not getattr( request.user, 'profile', None): login_redirect = redirect('/login/github?next=' + request.get_full_path()) return login_redirect if kudos_transfer.receive_txid: messages.info(request, _('This kudos has been received')) elif not is_authed: messages.error( request, f'This kudos is for {kudos_transfer.username} but you are logged in as {request.user.username}. Please logout and log back in as {kudos_transfer.username}.' ) elif did_fail: messages.info( request, f'This tx {kudos_transfer.txid}, failed. Please contact the sender and ask them to send the tx again.' ) elif not_mined_yet and not request.GET.get('receive_txid'): message = mark_safe( f'The <a href="https://etherscan.io/tx/{txid}">transaction</a> is still mining. ' 'Please wait a moment before submitting the receive form.') messages.info(request, message) elif request.GET.get('receive_txid') and not kudos_transfer.receive_txid: params = request.GET # db mutations try: if params['save_addr']: profile = get_profile(kudos_transfer.username.replace('@', '')) if profile: # TODO: Does this mean that the address the user enters in the receive form # Will overwrite an already existing preferred_payout_address? Should we # ask the user to confirm this? profile.preferred_payout_address = params[ 'forwarding_address'] profile.save() kudos_transfer.receive_txid = params['receive_txid'] kudos_transfer.receive_address = params['forwarding_address'] kudos_transfer.received_on = timezone.now() if request.user.is_authenticated: kudos_transfer.recipient_profile = request.user.profile kudos_transfer.save() record_user_action(kudos_transfer.username, 'new_kudos', kudos_transfer) record_user_action(kudos_transfer.from_username, 'receive_kudos', kudos_transfer) record_kudos_email_activity(kudos_transfer, kudos_transfer.username, 'receive_kudos') record_kudos_activity(kudos_transfer, kudos_transfer.username, 'receive_kudos') messages.success(request, _('This kudos has been received')) except Exception as e: messages.error(request, str(e)) logger.exception(e) params = { 'issueURL': request.GET.get('source'), 'class': 'receive', 'gas_price': round(recommend_min_gas_price_to_confirm_in_time(120), 1), 'kudos_transfer': kudos_transfer, 'title': f"Receive {kudos_transfer.kudos_token_cloned_from.humanized_name} Kudos" if kudos_transfer and kudos_transfer.kudos_token_cloned_from else _('Receive Kudos'), 'avatar_url': kudos_transfer.kudos_token_cloned_from.img_url if kudos_transfer and kudos_transfer.kudos_token_cloned_from else None, 'card_desc': f"You've received a {kudos_transfer.kudos_token_cloned_from.humanized_name} kudos!" if kudos_transfer and kudos_transfer.kudos_token_cloned_from else _('You\'ve received a kudos'), 'key': key, 'is_authed': is_authed, 'disable_inputs': kudos_transfer.receive_txid or not_mined_yet or not is_authed, 'tweet_text': urllib.parse.quote_plus( f"I just got a {kudos_transfer.kudos_token_cloned_from.humanized_name} Kudos on @gitcoin. " ) } return TemplateResponse(request, 'transaction/receive.html', params)
def getEditedMenuCount(appid): retlist = menuList.objects.filter(~Q(editflag=0), project_id=appid).values_list() return len(retlist)
def escalate_tickets(queues, verbose): """ Only include queues with escalation configured """ queryset = Queue.objects.filter(escalate_days__isnull=False).exclude( escalate_days=0) if queues: queryset = queryset.filter(slug__in=queues) for q in queryset: last = date.today() - timedelta(days=q.escalate_days) today = date.today() workdate = last days = 0 while workdate < today: if EscalationExclusion.objects.filter(date=workdate).count() == 0: days += 1 workdate = workdate + timedelta(days=1) req_last_escl_date = date.today() - timedelta(days=days) if verbose: print("Processing: %s" % q) for t in q.ticket_set.filter( Q(status=Ticket.OPEN_STATUS) | Q(status=Ticket.REOPENED_STATUS)).exclude(priority=1).filter( Q(on_hold__isnull=True) | Q(on_hold=False)).filter( Q(last_escalation__lte=req_last_escl_date) | Q(last_escalation__isnull=True, created__lte=req_last_escl_date)): t.last_escalation = timezone.now() t.priority -= 1 t.save() context = safe_template_context(t) t.send( { 'submitter': ('escalated_submitter', context), 'ticket_cc': ('escalated_cc', context), 'assigned_to': ('escalated_owner', context) }, fail_silently=True, ) if verbose: print(" - Esclating %s from %s>%s" % (t.ticket, t.priority + 1, t.priority)) f = FollowUp( ticket=t, title='Ticket Escalated', date=timezone.now(), public=True, comment=_('Ticket escalated after %s days' % q.escalate_days), ) f.save() tc = TicketChange( followup=f, field=_('Priority'), old_value=t.priority + 1, new_value=t.priority, ) tc.save()
def listTrans(request): if request.method == "GET": response = {"card_form": CardForm()} template = loader.get_template('transactions.html') return HttpResponse(template.render(response, request)) if request.method == "POST": user = UserCustom.objects.get(user_id__exact=request.user.pk) q = Q(org_id__exact=user.org.pk) data = None selection_parameters = None post = request.POST if "cmd" in post: if post["cmd"] == "update": if "data" in post: data = json.loads(post["data"]) if "selection_parameters" in post: selection_parameters = json.loads(post["selection_parameters"]) if selection_parameters is not None: if selection_parameters["type"]: q &= Q(type__exact=selection_parameters["type"]) if selection_parameters["dateFrom"]: q &= Q(date__date__gte=selection_parameters["dateFrom"]) if selection_parameters["dateTo"]: q &= Q(date__date__lte=selection_parameters["dateTo"]) if selection_parameters["card"]: try: card_id = Card.objects.get(code__exact=selection_parameters["card"]).pk except: card_id =False if card_id: q &= Q(card_id__exact=card_id) if selection_parameters["document_close_user"]: q &= Q(document_close_user__contains=selection_parameters["document_close_user"]) if selection_parameters["session"]: q &= Q(session__exact=selection_parameters["session"]) if selection_parameters["shop"]: q &= Q(shop__exact=selection_parameters["shop"]) if selection_parameters["workplace"]: q &= Q(workplace__exact=selection_parameters["workplace"]) if selection_parameters["doc_number"]: q &= Q(doc_number__exact=selection_parameters["doc_number"]) total = Transaction.objects.filter(q).count() if data["count"] > total: data["count"] = total trans = Transaction.objects.filter(q).order_by('-'+selection_parameters["sort"]).all()[data["start"]:data["start"]+data["count"]] resp_cards = [] for tran in trans: resp_cards.append( { "type": tran.return_type(), "date": tran.date.strftime('%Y-%m-%d / %H:%M'), "card": tran.card.code, "sum": tran.sum, "bonus_before": tran.bonus_before, "bonus_add": tran.bonus_add, "bonus_reduce": tran.bonus_reduce, "workplace": tran.workplace, "doc_number": tran.doc_number, "session": tran.session, "doc_external_id": tran.doc_external_id, "doc_close_user": tran.doc_close_user, "shop": tran.shop } ) response = {"result": "ok", "data": resp_cards, "total": total} return HttpResponse(json.dumps(response), content_type="application/json")
def edit_bench_bench_authorisation(request, matrix_id, bench_authorisation_id): data = get_header_data(request.user) authorisation = get_object_or_404(Authorisation, pk=bench_authorisation_id) if request.method == HTTP_POST: next_page = request.POST.get('next', '/') form = AuthorisationForm(request.POST, instance=authorisation) if form.is_valid(): authorisation = form.save(commit=False) if authorisation_exists_for_bench_and_permitted( authorisation.matrix, authorisation.permitted): authorisation_old = Authorisation.objects.get( Q(matrix=authorisation.matrix) & Q(permitted=authorisation.permitted)) if authorisation_old.authority != authorisation.authority: authorisation_old.authority = authorisation.authority authorisation_old.save() else: authorisation.save() return HttpResponseRedirect(next_page) else: text_flag = " for Bench CPW:" + format(int(matrix_id), '06d') messages.error(request, "Bench Authorisation Form is Invalid!") form.add_error(None, "Bench Authorisation Form is Invalid!") data.update({ 'text_flag': text_flag, 'form': form, 'authorisation': authorisation }) else: text_flag = " for Bench CPW:" + format(int(matrix_id), '06d') form = AuthorisationForm(instance=authorisation) form.fields['matrix'] = forms.ModelChoiceField( Matrix.objects.filter(id=matrix_id)) form.fields['matrix'].initial = matrix_id form.fields['permitted'] = forms.ModelChoiceField( User.objects.exclude(id=request.user.id).exclude( is_superuser=True)) data.update({ 'text_flag': text_flag, 'form': form, 'authorisation': authorisation }) return render(request, 'permissions/edit_bench_authorisation.html', data)
def author_posts_handler(request): #Posts that are visible to the currently authenticated user if (request.method == 'GET'): user = check_authenticate(request) if (user == None): return HttpResponse(status=403) try: author = Author.objects.get(user_id=user.id) except: return HttpResponse(status=404) host = "http://127.0.0.1:8000/" service_link = get_service_link() #Deal with friends and stuff here later. posts = Post.objects.filter( Q(author=author.id) | Q(visibility='PUBLIC')).order_by('-published') count = posts.count() #Check/get page size if 'size' not in request.GET: page_size = 25 else: try: page_size = int(request.GET['size']) except: page_size = 25 #Check/get current page if 'page' not in request.GET: current_page = 0 else: try: current_page = int(request.GET['page']) except: current_page = 0 returnjson = {} returnjson['query'] = "posts" returnjson['count'] = posts.count() returnjson['size'] = page_size if (current_page * page_size + page_size) < count: returnjson['next'] = service_link + "author/posts?page=" + str( (current_page + 1)) if (current_page != 0): returnjson['previous'] = service_link + "author/posts?page=" + str( (current_page - 1)) returnjson['posts'] = [] for item in posts[current_page * page_size:current_page * page_size + page_size]: workingdict = {} workingdict['title'] = item.title workingdict['source'] = item.source workingdict['origin'] = item.origin workingdict['description'] = item.description workingdict['contentType'] = item.contentType workingdict['content'] = item.content workingdict['id'] = item.id workingdict['published'] = item.published.strftime( "%Y-%m-%dT%H:%M:%S+00:00") workingdict['categories'] = item.categories.split(",") comments = item.comment_set.all().order_by('-published') workingdict['author'] = {} workingdict['author']['id'] = item.author.id workingdict['author']['host'] = item.author.host workingdict['author']['displayname'] = item.author.displayName workingdict['author']['url'] = item.author.url workingdict['author']['github'] = item.author.github workingdict['visibility'] = item.visibility workingdict['count'] = comments.count() workingdict['size'] = page_size workingdict['next'] = service_link + "posts/" + str( item.id) + "/comments" workingdict['comments'] = [] for comment in comments[:5]: workingcomment = {} workingcomment['author'] = {} workingcomment['author']['id'] = comment.author.id workingcomment['author']['host'] = comment.author.host workingcomment['author'][ 'displayName'] = comment.author.displayName workingcomment['author']['url'] = comment.author.url workingcomment['author']['github'] = comment.author.github workingcomment['comment'] = comment.comment workingcomment['contentType'] = comment.contentType workingcomment['published'] = comment.published.strftime( "%Y-%m-%dT%H:%M:%S+00:00") workingcomment['id'] = comment.id workingdict['comments'].append(workingcomment) returnjson['posts'].append(workingdict) return JsonResponse(returnjson) return HttpResponse(status=405)
def get_queryset(self): #solo_padre = Q(padre__isnull=True) #queryset = models.Escuela.objects.filter(solo_padre) queryset = models.Escuela.objects.all() query = self.request.query_params.get('query', None) filtro_conformada = self.request.query_params.get('conformada') filtro_region = self.request.query_params.get('localidad__distrito__region__numero') filtro_programa = self.request.query_params.get('programa') filtro_programa_in = self.request.query_params.get('programa_in') filtro_modalidad = self.request.query_params.get('modalidad') filtro_nivel = self.request.query_params.get('nivel') filtro_nivel_nombre = self.request.query_params.get('nivel__nombre') filtro_tipo_de_gestion = self.request.query_params.get('tipoDeGestion') filtro_piso = self.request.query_params.get('piso') filtro_llave = self.request.query_params.get('llave') filtro_distrito = self.request.query_params.get('distrito') filtro_localidad = self.request.query_params.get('localidad') filtro_robotica = self.request.query_params.get('robotica') filtro_sort = self.request.query_params.get('sort') if filtro_region: filtro = Q(localidad__distrito__region__numero=filtro_region) | Q(cue=60000000) queryset = queryset.filter(filtro) if filtro_modalidad: filtro = Q(modalidad=filtro_modalidad) queryset = queryset.filter(filtro) if filtro_conformada: if filtro_conformada.lower() == 'true': filtro_conformada = True else: filtro_conformada = False filtro = Q(conformada=filtro_conformada) queryset = queryset.filter(filtro) if filtro_programa: filtro = Q(programas__nombre=filtro_programa) queryset = queryset.filter(filtro) if filtro_programa_in: filtro_in = int(filtro_programa_in) filtro = Q(programas=filtro_in) queryset = queryset.filter(filtro) if filtro_nivel: filtro = Q(nivel=filtro_nivel) queryset = queryset.filter(filtro) if filtro_nivel_nombre: filtro = Q(nivel__nombre=filtro_nivel_nombre) queryset = queryset.filter(filtro) if filtro_tipo_de_gestion: filtro = Q(tipo_de_gestion=filtro_tipo_de_gestion) queryset = queryset.filter(filtro) if filtro_piso: if filtro_piso == 'funcionando': filtro = Q(piso__estado=True) else: filtro = Q(piso__estado=False) queryset = queryset.filter(filtro) if filtro_llave: if filtro_llave == 'sin-llave': filtro = Q(piso__llave='') else: filtro = ~Q(piso__llave='') queryset = queryset.filter(filtro) if filtro_distrito: filtro = Q(localidad__distrito=filtro_distrito) queryset = queryset.filter(filtro) if filtro_localidad: filtro = Q(localidad=filtro_localidad) queryset = queryset.filter(filtro) if query: filtro_cue = Q(cue__icontains=query) filtro_nombre = Q(nombre__icontains=query) filtro_localidad = Q(localidad__nombre__icontains=query) filtro_distrito = Q(localidad__distrito__nombre__icontains=query) filtro_nivel = Q(nivel__nombre__icontains=query) queryset = queryset.filter(filtro_cue | filtro_nombre | filtro_distrito | filtro_localidad | filtro_nivel) if filtro_sort: queryset = queryset.order_by(filtro_sort) if filtro_robotica: queryset = queryset.exclude(modalidad__nombre="Especial") return queryset
def get_queryset(self): query = self.request.GET.get('query') qs = Book.objects.filter(Q(title__icontains=query) | Q(authors__first_name__icontains=query) | Q( authors__middle_name__icontains=query) | Q(authors__last_name__icontains=query)).distinct() return qs
def in_menu_q(self): return Q(show_in_menus=True)
def reservations(self, timestamp): """Get the reservations for a given timestamp.""" return self.reservation_set.filter( Q(from_time__lte=timestamp), Q(to_time__gte=timestamp), )
def exact_type_q(self, klass): return Q(content_type=ContentType.objects.get_for_model(klass))
def products_inline(request, product_group_id, as_string=False, template_name="manage/property_groups/products_inline.html"): """Renders the products tab of the property groups management views. """ property_group = PropertyGroup.objects.get(pk=product_group_id) group_products = property_group.products.all() group_product_ids = [p.id for p in group_products] r = request.REQUEST s = request.session # If we get the parameter ``keep-filters`` or ``page`` we take the # filters out of the request resp. session. The request takes precedence. # The page parameter is given if the user clicks on the next/previous page # links. The ``keep-filters`` parameters is given is the users adds/removes # products. In this way we keeps the current filters when we needed to. If # the whole page is reloaded there is no ``keep-filters`` or ``page`` and # all filters are reset as they should. if r.get("keep-filters") or r.get("page"): page = r.get("page", s.get("property_group_page", 1)) filter_ = r.get("filter", s.get("filter")) category_filter = r.get("products_category_filter", s.get("products_category_filter")) else: page = r.get("page", 1) filter_ = r.get("filter") category_filter = r.get("products_category_filter") # The current filters are saved in any case for later use. s["property_group_page"] = page s["filter"] = filter_ s["products_category_filter"] = category_filter filters = Q() if filter_: filters &= Q(name__icontains=filter_) if category_filter: if category_filter == "None": filters &= Q(categories=None) elif category_filter == "All": pass else: # First we collect all sub categories and using the `in` operator category = lfs_get_object_or_404(Category, pk=category_filter) categories = [category] categories.extend(category.get_all_children()) filters &= Q(categories__in=categories) products = Product.objects.filter(filters) paginator = Paginator(products.exclude(pk__in=group_product_ids), 25) try: page = paginator.page(page) except EmptyPage: page = 0 result = render_to_string(template_name, RequestContext(request, { "property_group": property_group, "group_products": group_products, "page": page, "paginator": paginator, "filter": filter_ })) if as_string: return result else: return HttpResponse( simplejson.dumps({ "html": [["#products-inline", result]], }))
def parent_of_q(self, other): return Q(path=self.model._get_parent_path_from_path(other.path))
def landing_forms(request): id_form = FormId(prefix='a') form_idigent = FormIdigent(prefix='b') form_scholar = FormScholar() form_burial = FormBurial() form_business = FormBusiness() form_clearance = FormClearance() q_id = "" obj_id = 0 context = { 'form':id_form, 'indigent': form_idigent, 'scholar': form_scholar, 'burial' : form_burial, 'business': form_business, 'clearance': form_clearance, } if request.GET: query = request.GET.get('search_name') residents_query = [] split_queries = query.split(" ") for q in split_queries: filter_query = Resident.objects.filter( Q(first_name__icontains=q)| Q(middle_name__icontains=q)| Q(last_name__icontains=q)| Q(email_address__icontains=q) ).distinct() for qs in filter_query: residents_query.append(qs) resident_list = list(set(residents_query)) length_list = len(resident_list) if length_list > 1 or length_list < 1: print(resident_list) context = { 'form':id_form, 'indigent': form_idigent, 'scholar': form_scholar, 'burial' : form_burial, 'business': form_business, 'clearance': form_clearance, } else: q_id = resident_list[0] obj_id = q_id.id if IDForm.objects.filter(resident=obj_id).exists(): id_model = IDForm.objects.get(resident=obj_id) id_form = FormId(instance=id_model) if IndigencyForm.objects.filter(resident=obj_id).exists(): indigent_model = IndigencyForm.objects.get(resident=obj_id) form_idigent = FormIdigent(instance=indigent_model) context = { 'obj_result':q_id, 'value':obj_id, 'form':id_form, 'id_model': id_model, 'indigent': form_idigent, 'scholar': form_scholar, 'burial' : form_burial, 'business': form_business, 'clearance': form_clearance, } else: context = { 'obj_result':q_id, 'value':obj_id, 'form':id_form, 'indigent': form_idigent, 'scholar': form_scholar, 'burial' : form_burial, 'business': form_business, 'clearance': form_clearance, } if request.method == 'POST': post_data = request.POST.copy() post_data['a-resident'] = obj_id id_form = FormId(post_data, prefix='a') print("this id: " + str(post_data)) print("this form: " + str(id_form)) form_idigent = FormIdigent(request.POST, prefix='b') form_scholar = FormScholar(request.POST, prefix='c') form_burial = FormBurial(request.POST, prefix='d') form_business = FormBusiness(request.POST, prefix='e') form_clearance = FormClearance(request.POST, prefix='f') if id_form.is_valid(): id_form.cleaned_data['resident'] = obj_id a = id_form.save(commit=False) a = id_form.save() elif form_idigent.is_valid(): form_idigent.cleaned_data['resident'] = obj_id b = form_idigent.save() elif form_scholar.is_valid(): form_scholar.cleaned_data['resident'] = obj_id c = form_scholar.save() elif form_burial.is_valid(): form_burial.cleaned_data['resident'] = obj_id d = form_burial.save() elif form_business.is_valid(): form_business.cleaned_data['resident'] = obj_id e = form_business.save() elif form_clearance.is_valid(): form_clearance.cleaned_data['resident'] = obj_id f = form_clearance.save() # if 'Submit_id' in request.POST: # post_values = request.POST.copy() # post_values['resident_idform'] = obj_id # print(str(post_values)) # id_form = FormId(post_values) # if id_form.is_valid(): # id_form.save() else: context = { 'obj_result':q_id, 'value':obj_id, 'form':id_form, 'indigent': form_idigent, 'scholar': form_scholar, 'burial' : form_burial, 'business': form_business, 'clearance': form_clearance, } return render(request, 'landing/form_landing.html', context)
template_name="sponsor/sponsoring/del.html", success_url="/sponsors/list")), name="sponsor_del"), url(r'^export/adminmail', user_is_staff( EmailOutputView.as_view(queryset=User.objects.annotate( num_spon=Count("sponsorings")).filter( num_spon__gt=0).distinct(), template_name="mail.html")), name="sponsor_export_adminmail"), url(r'^export/allmail', user_is_staff( EmailOutputView.as_view(queryset=User.objects.annotate( num_spon=Count("sponsorings"), num_part=Count("sponsorparticipation")).filter( Q(num_part__gt=0)).distinct(), template_name="mail.html")), name="sponsor_export_allmail"), url(r'^export/boothmail', user_is_staff( EmailOutputView.as_view(queryset=User.objects.filter( sponsorparticipation__package__hasBooth=True).distinct(), template_name="mail.html")), name="sponsor_export_boothmail"), url(r'^export/recruitingmail', user_is_staff( EmailOutputView.as_view(queryset=User.objects.filter( sponsorparticipation__package__hasRecruitingEvent=True). distinct(), template_name="mail.html")), name="sponsor_export_recruitingmail"),
def instructor_view(request, instructor_id): """View for instructor page, showing all their courses taught.""" instructor: Instructor = get_object_or_404(Instructor, pk=instructor_id) stats: Dict[str, float] = Instructor.objects\ .filter(pk=instructor_id)\ .prefetch_related('review_set')\ .aggregate( avg_gpa=Avg('courseinstructorgrade__average'), avg_difficulty=Avg('review__difficulty'), avg_rating=( Avg('review__instructor_rating') + Avg('review__enjoyability') + Avg('review__recommendability') ) / 3) course_fields: List[str] = ['name', 'id', 'avg_rating', 'avg_difficulty', 'avg_gpa', 'last_taught'] courses: List[Dict[str, Any]] = Course.objects\ .filter(section__instructors=instructor, number__gte=1000)\ .prefetch_related('review_set')\ .annotate( subdepartment_name=F('subdepartment__name'), name=Concat( F('subdepartment__mnemonic'), Value(' '), F('number'), Value(' | '), F('title'), output_field=CharField(), ), avg_gpa=Avg('courseinstructorgrade__average', filter=Q(courseinstructorgrade__instructor=instructor)), avg_difficulty=Avg('review__difficulty', filter=Q(review__instructor=instructor)), avg_rating=( Avg('review__instructor_rating', filter=Q(review__instructor=instructor)) + Avg('review__enjoyability', filter=Q(review__instructor=instructor)) + Avg('review__recommendability', filter=Q(review__instructor=instructor)) ) / 3, last_taught=Concat( F('semester_last_taught__season'), Value(' '), F('semester_last_taught__year'), output_field=CharField(), ), ).values('subdepartment_name', *course_fields)\ .order_by('subdepartment_name', 'name') grouped_courses: Dict[str, List[Dict[str, Any]]] = {} for course in courses: # type: Dict[str, Any] course['avg_rating'] = safe_round(course['avg_rating']) course['avg_difficulty'] = safe_round(course['avg_difficulty']) course['avg_gpa'] = safe_round(course['avg_gpa']) course['last_taught'] = course['last_taught'].title() grouped_courses.setdefault(course['subdepartment_name'], []).append(course) context: Dict[str, Any] = { 'instructor': instructor, **{key: safe_round(value) for key, value in stats.items()}, 'courses': grouped_courses, } return render(request, 'instructor/instructor.html', context)
def get_history(request): response = {'status': -1} doc_type = request.GET.get('doc_type') doc_text = request.GET.get('doc_text') connector_id = request.GET.get('doc_connector') page = min(int(request.GET.get('page', 1)), 100) limit = min(int(request.GET.get('limit', 50)), 100) is_notification_manager = request.GET.get('is_notification_manager', 'false') == 'true' if is_notification_manager: docs = Document2.objects.get_tasks_history(user=request.user) else: docs = Document2.objects.get_history(doc_type='query-%s' % doc_type, connector_id=connector_id, user=request.user) if doc_text: docs = docs.filter( Q(name__icontains=doc_text) | Q(description__icontains=doc_text) | Q(search__icontains=doc_text)) # Paginate docs = docs.order_by('-last_modified') response['count'] = docs.count() docs = __paginate(page, limit, queryset=docs)['documents'] history = [] for doc in docs: notebook = Notebook(document=doc).get_data() if 'snippets' in notebook: statement = notebook[ 'description'] if is_notification_manager else _get_statement( notebook) history.append({ 'name': doc.name, 'id': doc.id, 'uuid': doc.uuid, 'type': doc.type, 'data': { 'statement': statement[:1001] if statement else '', 'lastExecuted': notebook['snippets'][0].get('lastExecuted', -1), 'status': notebook['snippets'][0]['status'], 'parentSavedQueryUuid': notebook.get('parentSavedQueryUuid', '') } if notebook['snippets'] else {}, 'absoluteUrl': doc.get_absolute_url(), }) else: LOG.error('Incomplete History Notebook: %s' % notebook) response['history'] = sorted(history, key=lambda row: row['data']['lastExecuted'], reverse=True) response['message'] = _('History fetched') response['status'] = 0 return JsonResponse(response)
def getAccountType(user): return AccountType.objects.filter(Q(user=None) | Q(user=user)).values_list('name', flat=True)
def search_7d(self): """Search programmes for the next 7 days""" if self.recherche: q_recherche = [ Q(titres__nom__unaccent__icontains=self.recherche), Q(titre_informatif__unaccent__icontains=self.recherche), Q(description__unaccent__icontains=self.recherche), Q(realisateur__nom__unaccent__icontains=self.recherche), Q(acteurs__nom__unaccent__icontains=self.recherche), Q(acteurs__role__unaccent__icontains=self.recherche), Q(scenariste__nom__unaccent__icontains=self.recherche), Q(categories__nom__unaccent__icontains=self.recherche), Q(paysrealisation__nom__unaccent__icontains=self.recherche), Q(critique__unaccent__icontains=self.recherche), ] q_list = [] if self.titre is not None: q_list.append(Q(titres__nom__unaccent__icontains=self.titre)) if self.titre_informatif is not None: q_list.append( Q(titre_informatif__unaccent__icontains=self.titre_informatif)) if self.description is not None: q_list.append(Q(description__unaccent__icontains=self.description)) if self.realisateur is not None: q_list.append( Q(realisateur__nom__unaccent__icontains=self.realisateur)) if self.acteur is not None: q_list.append(Q(acteurs__nom__unaccent__icontains=self.acteur)) if self.role is not None: q_list.append(Q(acteurs__role__unaccent__icontains=self.role)) if self.scenariste is not None: q_list.append( Q(scenariste__nom__unaccent__icontains=self.scenariste)) if self.date_realisation is not None: q_list.append(Q(date_realisation=self.date_realisation)) if self.categorie is not None: q_list.append( Q(categories__nom__unaccent__icontains=self.categorie)) if self.serie is not None: q_list.append(Q(series__serie=self.serie)) if self.episode is not None: q_list.append(Q(series__episode=self.episode)) if self.partie is not None: q_list.append(Q(series__partie=self.partie)) if self.pays_realisation is not None: q_list.append( Q(paysrealisation__nom__unaccent__icontains=self. pays_realisation)) if self.public is not None: q_list.append(Q(public__lte=self.public)) if self.aide_sourd is not None: q_list.append(Q(aide_sourd=self.aide_sourd)) if self.note is not None: q_list.append(Q(note__gte=self.note)) if self.critique is not None: q_list.append(Q(critique__unaccent__icontains=self.critique)) if len(q_list) > 0: programmes = Programmes.objects.filter( reduce(operator.and_, q_list), chaines__in=[chaine.id for chaine in self.chaines], ).order_by("date_debut") if self.recherche and len(q_list) == 0: programmes = Programmes.objects.filter( reduce(operator.or_, q_recherche), chaines__in=[chaine.id for chaine in self.chaines], ).order_by("date_debut") elif self.recherche and len(q_list) > 0: programmes_recherche = Programmes.objects.filter( reduce(operator.or_, q_recherche), id__in=[prog.id for prog in programmes], ).order_by("date_debut") programmes = programmes_recherche elif (self.recherche is None and len(q_list) == 0): programmes = [] elif (self.recherche == "" and len(q_list) == 0): programmes = [] """To remove duplicates:""" programmes = list(dict.fromkeys(programmes)) programmes_7d = [] for progs in programmes: if progs.date_debut >= make_aware(datetime.datetime.now()): programmes_7d.append(progs) programmes_7d = programmes_7d[:self.max_resultats] return programmes_7d
def test_geodetic_distance_lookups(self): """ Test distance lookups on geodetic coordinate systems. """ # Line is from Canberra to Sydney. Query is for all other cities within # a 100km of that line (which should exclude only Hobart & Adelaide). line = GEOSGeometry('LINESTRING(144.9630 -37.8143,151.2607 -33.8870)', 4326) dist_qs = AustraliaCity.objects.filter(point__distance_lte=(line, D(km=100))) self.assertEqual(9, dist_qs.count()) self.assertEqual([ 'Batemans Bay', 'Canberra', 'Hillsdale', 'Melbourne', 'Mittagong', 'Shellharbour', 'Sydney', 'Thirroul', 'Wollongong' ], self.get_names(dist_qs)) # Too many params (4 in this case) should raise a ValueError. queryset = AustraliaCity.objects.filter( point__distance_lte=('POINT(5 23)', D(km=100), 'spheroid', '4')) with self.assertRaises(ValueError): len(queryset) # Not enough params should raise a ValueError. with self.assertRaises(ValueError): len( AustraliaCity.objects.filter( point__distance_lte=('POINT(5 23)', ))) # Getting all cities w/in 550 miles of Hobart. hobart = AustraliaCity.objects.get(name='Hobart') qs = AustraliaCity.objects.exclude(name='Hobart').filter( point__distance_lte=(hobart.point, D(mi=550))) cities = self.get_names(qs) self.assertEqual(cities, ['Batemans Bay', 'Canberra', 'Melbourne']) # Cities that are either really close or really far from Wollongong -- # and using different units of distance. wollongong = AustraliaCity.objects.get(name='Wollongong') d1, d2 = D(yd=19500), D(nm=400) # Yards (~17km) & Nautical miles. # Normal geodetic distance lookup (uses `distance_sphere` on PostGIS. gq1 = Q(point__distance_lte=(wollongong.point, d1)) gq2 = Q(point__distance_gte=(wollongong.point, d2)) qs1 = AustraliaCity.objects.exclude(name='Wollongong').filter(gq1 | gq2) # Geodetic distance lookup but telling GeoDjango to use `distance_spheroid` # instead (we should get the same results b/c accuracy variance won't matter # in this test case). querysets = [qs1] if connection.features.has_distance_spheroid_method: gq3 = Q(point__distance_lte=(wollongong.point, d1, 'spheroid')) gq4 = Q(point__distance_gte=(wollongong.point, d2, 'spheroid')) qs2 = AustraliaCity.objects.exclude( name='Wollongong').filter(gq3 | gq4) querysets.append(qs2) for qs in querysets: cities = self.get_names(qs) self.assertEqual( cities, ['Adelaide', 'Hobart', 'Shellharbour', 'Thirroul'])
def default_ticket_type(): Q = TicketType.objects.order_by('-price') if Q.count() > 0: return Q[0] else: return None
def create(request): room_type = '' start_date = '' end_date = '' start_date_value = '' end_date_value = '' if request.GET.get('room_type'): room_type = request.GET['room_type'] if room_type == 'meeting': cat = 'Meeting Space' elif room_type == 'tele': cat = 'Teleconference Room' elif room_type == 'work': cat = 'Workspaces' elif room_type == 'misc': cat = 'Misc' else: cat = 'all' if cat == 'all': rooms = Room.objects.filter() else: rooms = Room.objects.filter(category=cat) elif request.GET.get('room_id'): room_id = request.GET['room_id'] print('room_id: {}'.format(room_id)) start_book = request.GET['start_book'] end_book = request.GET['end_book'] room = Room.objects.get(pk=room_id) bookings = Booking.objects.filter(room=room) response = [] for booking in bookings: if request.user == booking.owner: owner = 'true' else: owner = 'false' title = booking.title start_book = booking.start_book end_book = booking.end_book response.append([owner, title, start_book, end_book]) response = json.dumps(response, default=datetime_handler) return HttpResponse(response) elif request.GET.get('type') == 'search': start_book = request.GET['date_start'] end_book = request.GET['date_end'] if start_book != '' and end_book != '': room_ids= Booking.objects.values_list('room__id', flat=True).filter( Q(start_book__gte=start_book, start_book__lt=end_book) | Q(end_book__gt=start_book, end_book__lte=end_book) | Q(start_book__gte=start_book, end_book__lte=end_book) | Q(start_book__lte=start_book, end_book__gte=end_book)) rooms = Room.objects.filter(~Q(id__in=set(room_ids))) start_date = datetime.datetime.strptime(start_book,'%Y-%m-%d %H:%M').strftime('%I%p, %d %B %Y') start_date_value = start_book end_date = datetime.datetime.strptime(end_book,'%Y-%m-%d %H:%M').strftime('%I%p, %d %B %Y') end_date_value = end_book else: rooms = Room.objects.all() else: rooms = Room.objects.all() context = { 'rooms': rooms, 'room_type': room_type, 'start_date': start_date, 'end_date': end_date, 'start_date_value': start_date_value, 'end_date_value': end_date_value, 'navbar_pages': navbar_pages, } if request.POST: owner = request.user room_id = request.POST['room_id'] room = Room.objects.get(pk=room_id) date_start = request.POST['date_start'] date_end = request.POST['date_end'] title = request.POST['title'] try: booking = Booking.objects.create(room=room, owner=owner, title=title, start_book=date_start, end_book=date_end) response = [] title = booking.title room = booking.room.name start_book = booking.start_book end_book = booking.end_book response = [room, title, start_book, end_book] response = json.dumps(response) return HttpResponse(response) except: return HttpResponse('error') return render(request, 'officespace/create.html', context)