def get_context_data(self, **kwargs): """ Configures quest set filters and table information. Returns a context dictionary. """ context = super(QuestMixin, self).get_context_data(**kwargs) context['owner'] = Relation.objects.owned_by(self.request.user) context['owned'] = Quest.objects.owned_by(self.request.user) context['assigned'] = Quest.objects.assigned_to(self.request.user) context['proposed'] = Quest.objects.proposed_by(self.request.user) context['pending'] = Quest.objects.pending_for(self.request.user) context['completed'] = Quest.objects.completed_for(self.request.user) context['waiting'] = Quest.objects.waiting_for(self.request.user) context['owned_table'] = OwnedQuestTable(context['owned']) context['assigned_table'] = AssignedQuestTable(context['assigned']) context['proposed_table'] = ProposedQuestTable(context['proposed']) context['pending_table'] = PendingQuestTable(context['pending']) context['completed_table'] = CompletedQuestTable(context['completed']) context['waiting_table'] = WaitingQuestTable(context['waiting']) requestConfig = RequestConfig(self.request, paginate={ "per_page": 10, }) requestConfig.configure(context['owned_table']) requestConfig.configure(context['assigned_table']) requestConfig.configure(context['proposed_table']) requestConfig.configure(context['pending_table']) requestConfig.configure(context['completed_table']) requestConfig.configure(context['waiting_table']) return context
def ondemand(request): """provides on demand portion of site """ now = datetime.today() channels_filtered=request.GET.getlist('channels') type_filtered=request.GET.get('type') #switch the value of type filtered to the other so that it can properly exclude the opposite value if type_filtered=="Tv": type_filtered="Movie" elif type_filtered=="Movie": type_filtered="Tv" if channels_filtered: #filters out any channel that was passed in the Get request as checkmarked #channels_removed_obj_list = [obj for obj in Titles.objects.all() if any(name in obj.channel for name in channels_filtered)] ob_list_channelsremoved = Ondemand_Titles.objects.exclude(reduce(lambda x, y: x | y, [Q(channel__contains=word) for word in channels_filtered])) else: ob_list_channelsremoved=Ondemand_Titles.objects.all() config = RequestConfig(request,paginate={"per_page":40 }) table1= OndemandTable(ob_list_channelsremoved) config.configure(table1) return render(request, 'ondemand.html', {'table1':table1,'current_date':now,})
def filters_list(request): public_view = PublicFiltersView(request, model=TestRunFilter, table_class=PublicFiltersTable) prefix = "public_" public_filters_table = PublicFiltersTable(public_view.get_table_data(prefix), prefix=prefix) config = RequestConfig(request) config.configure(public_filters_table) search_data = public_filters_table.prepare_search_data(public_view) discrete_data = public_filters_table.prepare_discrete_data(public_view) terms_data = public_filters_table.prepare_terms_data(public_view) times_data = public_filters_table.prepare_times_data(public_view) user_filters_table = None if request.user.is_authenticated(): user_view = UserFiltersView(request, model=TestRunFilter, table_class=UserFiltersTable) prefix = "user_" user_filters_table = UserFiltersTable(user_view.get_table_data(prefix), prefix=prefix) config.configure(user_filters_table) search_data.update(user_filters_table.prepare_search_data(user_view)) discrete_data.update(user_filters_table.prepare_discrete_data(user_view)) terms_data.update(user_filters_table.prepare_terms_data(user_view)) return render_to_response( "dashboard_app/filters_list.html", { "user_filters_table": user_filters_table, "public_filters_table": public_filters_table, "terms_data": terms_data, "search_data": search_data, "times_data": times_data, "discrete_data": discrete_data, "bread_crumb_trail": BreadCrumbTrail.leading_to(filters_list), }, RequestContext(request), )
class TableHelperMixin(object): """ provide a function add_table that you can call in a get_context_data to add and configure tables from querysets """ table_context_name_base = 'mtable' mtables = 0 tconfig = None def get_new_table_context_name(self): return '{}{}'.format(self.table_context_name_base, self.mtables) def add_table(self, context, qs, table_class=None, with_report=False, context_name=None, **kwargs): """ context = context from get_context_data (dict) qs = the qs for the table table_class = Table class to use, auto generated from model if not provided. kwargs = will be used in the auto generation table class. with_report = FIXME: not showing export buttons right now. context_name = specify context name for the table """ if not self.mtables: self.mtables = 0 if not self.tconfig: self.config = RequestConfig(self.request) convert_to_list = kwargs.get('convert_to_list') if not table_class: if with_report: table_class = create_report_table(qs.model, **kwargs) else: table_class = create_model_table(qs.model, **kwargs) if convert_to_list: table_fields = kwargs.get('table_fields', []) if table_fields: qs_list = self.convert_qs_to_list(qs, table_fields) else: qs_list = qs.values() qs_list = list(qs_list) table = table_class(qs_list) else: table = table_class(qs) self.config.configure(table) self.mtables = self.mtables + 1 context[context_name or self.get_new_table_context_name()] = table return table def convert_qs_to_list(self, qs, table_fields): qs_list = [] for obj in qs: obj_dict = {} for f in table_fields: x = getattr(obj, f) if hasattr(x, '__call__'): x = x() obj_dict[f] = x qs_list.append(obj_dict) return qs_list
def get_journal(request): config = RequestConfig(request) tasks = TaskResult.objects.filter(created_by_user=request.user) table = JournalTable(tasks) table.paginate(page=request.GET.get("page", 1), per_page=25) config.configure(table) return render(request, 'webservice/journal.html', {'table': table, 'section': 'journal'})
def show_settings(request): config = RequestConfig(request) template = loader.get_template('settings.html') taxtable = TaxTable(models.TaxRate.objects.all(), prefix="tax-") billingcycleable = BillingCycleTable( models.CustomerBillingCycle.objects.all(), prefix="billingcycle-") unittable = UnitTable(models.Unit.objects.all(), prefix="unit-") customergrouptable = CustomerGroupTable(models.CustomerGroup.objects.all(), prefix="customergroup-") productcategorytable = ProductCategoryTable( cartridge_models.Category.objects.all(), prefix="productcategory-") config.configure(taxtable) config.configure(billingcycleable) config.configure(unittable) config.configure(customergrouptable) config.configure(productcategorytable) taxtable.paginate(page=request.GET.get('page', 1), per_page=5) billingcycleable.paginate(page=request.GET.get('page', 1), per_page=5) unittable.paginate(page=request.GET.get('page', 1), per_page=5) customergrouptable.paginate(page=request.GET.get('page', 1), per_page=5) productcategorytable.paginate(page=request.GET.get('page', 1), per_page=5) context = RequestContext( request, { 'taxtable': taxtable, 'billingcycletable': billingcycleable, 'unittable': unittable, 'customergrouptable': customergrouptable, 'productcategorytable': productcategorytable }) return HttpResponse(template.render(context))
def ondemand(request): """provides on demand portion of site """ now = datetime.today() channels_filtered = request.GET.getlist('channels') type_filtered = request.GET.get('type') #switch the value of type filtered to the other so that it can properly exclude the opposite value if type_filtered == "Tv": type_filtered = "Movie" elif type_filtered == "Movie": type_filtered = "Tv" if channels_filtered: #filters out any channel that was passed in the Get request as checkmarked #channels_removed_obj_list = [obj for obj in Titles.objects.all() if any(name in obj.channel for name in channels_filtered)] ob_list_channelsremoved = Ondemand_Titles.objects.exclude( reduce(lambda x, y: x | y, [Q(channel__contains=word) for word in channels_filtered])) else: ob_list_channelsremoved = Ondemand_Titles.objects.all() config = RequestConfig(request, paginate={"per_page": 40}) table1 = OndemandTable(ob_list_channelsremoved) config.configure(table1) return render(request, 'ondemand.html', { 'table1': table1, 'current_date': now, })
def prefs(req, user=None): ''' Show the preference page of the specified user. If requesting to show user that is not current session, the superuser permission are required. ''' if user==None: user=req.user.username if user!=req.user.username and not req.user.is_superuser: if req.user.username!=user: return HttpResponseForbidden('<h1>403-Forbidden</h1>') user=getObj(get_user_model(), username=user) if req.method=='POST': newPwd=req.POST.get('newPwd', None) if newPwd and newPwd==req.POST.get('rePwd', None): user.set_password(newPwd) user.save() auth_logout(req) return redirect('webframe:prefs', user=user) params=dict() params['preference']=PreferenceTable(Preference.objects.filter(owner=req.user, parent__isnull=True)) params['config']=PreferenceTable(Preference.objects.filter(owner__isnull=True, parent__isnull=True)) rc=RequestConfig(req) rc.configure(params['preference']) rc.configure(params['config']) params['currentuser']=user if req.user.has_perm('webframe.add_config') or req.user.has_perm('webframe.change.config'): m=hashlib.md5() m.update(user.username.encode('utf-8')) m.update(CONFIG_KEY.encode('utf-8')) params['config_key']=m.hexdigest() return render(req, getattr(settings, 'TMPL_PREFERENCES', 'webframe/preferences.html'), params)
def query_display(request, username, name): query = get_object_or_404(Query, owner__username=username, name=name) view = QueryResultView( content_type=query.content_type, conditions=query.querycondition_set.all(), request=request, model=query.content_type.model_class(), table_class=QUERY_CONTENT_TYPE_TABLE[query.content_type.model] ) table = QUERY_CONTENT_TYPE_TABLE[query.content_type.model]( view.get_table_data() ) config = RequestConfig(request, paginate={"per_page": table.length}) config.configure(table) return render_to_response( 'lava_results_app/query_display.html', { 'query': query, 'entity': query.content_type.model, 'conditions': _join_conditions(query), 'query_table': table, 'terms_data': table.prepare_terms_data(view), 'search_data': table.prepare_search_data(view), 'discrete_data': table.prepare_discrete_data(view), 'bread_crumb_trail': BreadCrumbTrail.leading_to( query_display, username=username, name=name), 'context_help': BreadCrumbTrail.leading_to(query_list), }, RequestContext(request) )
def get_context_data(self, **kwargs): """ Configures quest set filters and table information. Returns a context dictionary. """ context = super(QuestMixin, self).get_context_data(**kwargs) context['owner'] = Relation.objects.owned_by(self.request.user) context['owned'] = Quest.objects.owned_by(self.request.user) context['assigned'] = Quest.objects.assigned_to(self.request.user) context['proposed'] = Quest.objects.proposed_by(self.request.user) context['pending'] = Quest.objects.pending_for(self.request.user) context['completed'] = Quest.objects.completed_for(self.request.user) context['waiting'] = Quest.objects.waiting_for(self.request.user) context['owned_table'] = OwnedQuestTable(context['owned']) context['assigned_table'] = AssignedQuestTable(context['assigned']) context['proposed_table'] = ProposedQuestTable(context['proposed']) context['pending_table'] = PendingQuestTable(context['pending']) context['completed_table'] = CompletedQuestTable(context['completed']) context['waiting_table'] = WaitingQuestTable(context['waiting']) requestConfig = RequestConfig(self.request, paginate={"per_page": 10,}) requestConfig.configure(context['owned_table']) requestConfig.configure(context['assigned_table']) requestConfig.configure(context['proposed_table']) requestConfig.configure(context['pending_table']) requestConfig.configure(context['completed_table']) requestConfig.configure(context['waiting_table']) return context
def show_settings(request): config = RequestConfig(request) template = loader.get_template('settings.html') taxtable = TaxTable(TaxRate.objects.all(), prefix="tax-") billingcycleable = BillingCycleTable(CustomerBillingCycle.objects.all(), prefix="billingcycle-") unittable = UnitTable(Unit.objects.all(), prefix="unit-") customergrouptable = CustomerGroupTable(CustomerGroup.objects.all(), prefix="customergroup-") productcategorytable = ProductCategoryTable(ProductCategory.objects.all(), prefix="productcategory-") config.configure(taxtable) config.configure(billingcycleable) config.configure(unittable) config.configure(customergrouptable) config.configure(productcategorytable) taxtable.paginate(page=request.GET.get('page', 1), per_page=5) billingcycleable.paginate(page=request.GET.get('page', 1), per_page=5) unittable.paginate(page=request.GET.get('page', 1), per_page=5) customergrouptable.paginate(page=request.GET.get('page', 1), per_page=5) productcategorytable.paginate(page=request.GET.get('page', 1), per_page=5) context = RequestContext(request, { 'taxtable': taxtable, 'billingcycletable': billingcycleable, 'unittable': unittable, 'customergrouptable': customergrouptable, 'productcategorytable': productcategorytable }) return HttpResponse(template.render(context))
def get_queryset(self): queryset = super(SelectRelatedMixin, self).get_queryset() config = RequestConfig(self.request) user = User.objects.get(pk=self.request.user.id) customer = HistoryTable(queryset.select_related(*self.select_related).filter(customer=user.customer)) config.configure(customer) return customer
def get(self, request, *args, **kwargs): context = self.get_context_data(**kwargs) config = RequestConfig(request) table = self.table_class(self.object_list) config.configure(table) table.paginate(page=request.GET.get('page', 1), per_page=self.table_pagination) context[self.context_table_name] = table return self.render_to_response(context)
def coordinate(request): all = Interval.objects.all() coordinates= CoordinateTable(all) avg_counts = CoordinateTable(Read_alignment.objects.annotate(Avg('read_counts'))) config = RequestConfig(request) config.configure(coordinates) config.configure(avg_counts) return render(request,"srb/coordinate.html",{'coordinates':coordinates,'avg_counts':avg_counts })
def get(self, request, *args, **kwargs): context = self.get_context_data(**kwargs) config = RequestConfig(request) table = self.table_class(self.object_list) config.configure(table) table.paginate(page=request.GET.get('page', 1), per_page=self.table_pagination) context[self.context_table_name] = table return self.render_to_response(context)
def query_display(request, username, name): query = get_object_or_404(Query, owner__username=username, name=name) if not request.user.is_superuser: if not query.is_published and query.owner != request.user: raise PermissionDenied view = QueryResultView( query=query, request=request, model=query.content_type.model_class(), table_class=QUERY_CONTENT_TYPE_TABLE[query.content_type.model_class()], ) table = QUERY_CONTENT_TYPE_TABLE[query.content_type.model_class()]( query, request.user, view.get_table_data()) try: config = RequestConfig(request, paginate={"per_page": table.length}) config.configure(table) except ProgrammingError: raise QueryViewDoesNotExistError( "Query view does not exist. Please contact query owner or system " "administrator.") omitted = [ result.content_object for result in QueryOmitResult.objects.filter(query=query) ] template = loader.get_template("lava_results_app/query_display.html") return HttpResponse( template.render( { "query": query, "entity": query.content_type.model, "conditions": Query.serialize_conditions(query.querycondition_set.all()), "omitted": omitted, "query_table": table, "terms_data": table.prepare_terms_data(view), "search_data": table.prepare_search_data(view), "discrete_data": table.prepare_discrete_data(view), "bread_crumb_trail": BreadCrumbTrail.leading_to( query_display, username=username, name=name), "context_help": ["lava-queries-charts"], }, request=request, ))
def get_queryset(self): queryset = super(SelectRelatedMixin, self).get_queryset() config = RequestConfig(self.request) user = User.objects.get(pk=self.request.user.id) customer = HistoryTable( queryset.select_related(*self.select_related).filter( customer=user.customer)) config.configure(customer) return customer
def borrowers_listing(request): config = RequestConfig(request) table1 = BorrowersTable(Borrowers.objects.all(), prefix='1-') table2 = BorrowersTable(Borrowers.objects.all(), prefix='2-') config.configure(table1) config.configure(table2) return render(request, 'intranet/borrowers-listing.html', { 'table1': table1, 'table2': table2 })
def inventoryOrderReportsView(request, pk=None): permissions = get_object_or_404(UserPermissions, user=request.user) order = get_object_or_404(InventoryOrder, pk=pk) order_reports = InventoryRoomReportTable(InventoryRoomReport.objects.filter(order=order), prefix='rr-') done_rooms = InventoryRoomReport.objects.filter(order=order).values_list('room__id', flat=True) remaining_rooms = RoomTableNoEdit(Room.objects.exclude(id__in=done_rooms), prefix='r-') config = RequestConfig(request) config.configure(order_reports) config.configure(remaining_rooms) return render(request, 'inventoryOrderReports.html', { 'permissions' : permissions , 'order_reports' : order_reports , 'remaining_rooms' : remaining_rooms , 'order' : order , 'finish' : Room.objects.exclude(id__in=done_rooms).exists() })
def query_custom(request): try: content_type = Query.get_content_type(request.GET.get("entity")) except InvalidContentTypeError as e: messages.error(request, e) raise Http404() if content_type.model_class() not in QueryCondition.RELATION_MAP: messages.error( request, "Wrong table name in entity param. Please refer to query docs.") raise Http404() try: conditions = Query.parse_conditions(content_type, request.GET.get("conditions")) except InvalidConditionsError as e: messages.error(request, e) raise Http404() view = QueryCustomResultView( content_type=content_type, conditions=conditions, request=request, model=content_type.model_class(), table_class=QUERY_CONTENT_TYPE_TABLE[content_type.model_class()] ) try: table = QUERY_CONTENT_TYPE_TABLE[content_type.model_class()]( None, request.user, view.get_table_data() ) except (FieldDoesNotExist, FieldError) as e: messages.error(request, e) raise Http404() config = RequestConfig(request, paginate={"per_page": table.length}) config.configure(table) template = loader.get_template('lava_results_app/query_custom.html') return HttpResponse(template.render( { 'query_table': table, 'conditions': conditions, 'terms_data': table.prepare_terms_data(view), 'search_data': table.prepare_search_data(view), 'discrete_data': table.prepare_discrete_data(view), 'bread_crumb_trail': BreadCrumbTrail.leading_to(query_custom), 'context_help': ['lava-queries-charts'], }, request=request) )
def query_custom(request): try: content_type = Query.get_content_type(request.GET.get("entity")) except InvalidContentTypeError as e: messages.error(request, e) raise Http404() if content_type.model_class() not in QueryCondition.RELATION_MAP: messages.error( request, "Wrong table name in entity param. Please refer to query docs.") raise Http404() try: conditions = Query.parse_conditions(content_type, request.GET.get("conditions")) except InvalidConditionsError as e: messages.error(request, e) raise Http404() view = QueryCustomResultView( content_type=content_type, conditions=conditions, request=request, model=content_type.model_class(), table_class=QUERY_CONTENT_TYPE_TABLE[content_type.model_class()] ) try: table = QUERY_CONTENT_TYPE_TABLE[content_type.model_class()]( None, request.user, view.get_table_data() ) except (FieldDoesNotExist, FieldError) as e: messages.error(request, e) raise Http404() config = RequestConfig(request, paginate={"per_page": table.length}) config.configure(table) template = loader.get_template('lava_results_app/query_custom.html') return HttpResponse(template.render( { 'query_table': table, 'conditions': conditions, 'terms_data': table.prepare_terms_data(view), 'search_data': table.prepare_search_data(view), 'discrete_data': table.prepare_discrete_data(view), 'bread_crumb_trail': BreadCrumbTrail.leading_to(query_custom), 'context_help': ['lava-queries-charts'], }, request=request) )
def equipments(request): q = request.GET.get('q') if ( q is None ) : table = EquipmentTable(Equipment.objects.all()) q='' else: table = EquipmentTable(Equipment.objects.filter(Q(serial_number__exact=q) | Q(location_business_name__contains=q))) config = RequestConfig(request, paginate={"per_page": 10}) config.configure(table) return render(request, "ems/equipment_table.html", {"table": table, 'search_var':q})
def advanced_search_view(request): """Search is done with function """ context = {} table_config = RequestConfig(request, paginate={'per_page': 30}) table = None man = '' prod = '' family = '' bus = '' key_words = '' user = '' if request.method == 'GET': form = DeviceServerSearchForm(request.GET) if form.is_valid(): # Do something with the data man = form.cleaned_data.get('manufacturer', None) prod = form.cleaned_data.get('product', None) family = form.cleaned_data.get('family', None) bus = form.cleaned_data.get('bus', None) key_words = form.cleaned_data.get('key_words', None) user = form.cleaned_data.get('user', None) q = dsc_models.filtered_device_servers(manufacturer=man, product=prod, family=family, bus=bus, key_words=key_words, user=user) device_servers = q.distinct().order_by('name') table = DeviceServerSearchTable(device_servers) if table is not None: table_config.configure(table) form = DeviceServerSearchForm(initial=request.GET) if 'breadcrumb_extra_ancestors' not in context: context['breadcrumb_extra_ancestors'] = [] context['breadcrumb_extra_ancestors'].append( (request.get_full_path(), 'Search')) context.update({ 'form': form, 'table': table, 'manufacturer': man, 'product': prod, 'family': family, 'bus': bus, 'key_words': key_words, 'dsc_user': user, }) return render(request, 'dsc/deviceserver_advanced_search.html', context)
def closed_processes(request): closed_processes = (Process.objects.for_user(request.user).filter( end_date__isnull=False).select_related("candidate", "contract_type")) closed_processes_table = ProcessEndTable(closed_processes, prefix="c") config = RequestConfig(request) config.configure(closed_processes_table) context = {"title": _("Closed processes"), "table": closed_processes_table} return render(request, "interview/single_table.html", context)
def addressDetailView(request, pk=None): if pk: address = get_object_or_404(Address, id=pk) permissions = get_object_or_404(UserPermissions, user=request.user) if permissions.is_admin: rooms = RoomTable(Room.objects.filter(address=address), prefix='r-') else: rooms = RoomTableNoEdit(Room.objects.filter(address=address), prefix='r-') entries = EntryTable(Entry.objects.filter(room__address=address), prefix='e-') config = RequestConfig(request) config.configure(rooms) config.configure(entries) return render(request, 'addressDetails.html', { 'address' : address , 'rooms' : rooms , 'entries' : entries }) return HttpResponseRedirect(reverse('address'))
def result(request, task_id=None): # read from celery the results # save CSV file task_results = celery_app.AsyncResult(task_id).get() scoring_df = pd.read_csv(StringIO(task_results)) scoring_df = scoring_df.fillna('') scoring_results_table = ScoringTable(scoring_df.to_dict('records')) config = RequestConfig(request) config.paginate = False config.configure(scoring_results_table) return render_to_response('review_scoring/result.html', {"scoring_results": scoring_results_table, "task_id": task_id, "scoring_plot": create_html_plot_tooltip(scoring_df)}, context_instance=RequestContext(request))
def report(request): if not request.user.trusted: return http.HttpResponseForbidden("Forbidden") report_tables = [ report_getter(prefix=f'{report_key}_') for (report_key, report_getter) in REPORT_TABLES ] table_config = RequestConfig(request) for report_table in report_tables: table_config.configure(report_table) return TemplateResponse(request, 'review/report.html', { 'program_year': settings.REVIEW_PROGRAM_YEAR, 'reports': report_tables, })
def query_display(request, username, name): query = get_object_or_404(Query, owner__username=username, name=name) if not request.user.is_superuser: if not query.is_published and query.owner != request.user: raise PermissionDenied view = QueryResultView( query=query, request=request, model=query.content_type.model_class(), table_class=QUERY_CONTENT_TYPE_TABLE[query.content_type.model_class()] ) table = QUERY_CONTENT_TYPE_TABLE[query.content_type.model_class()]( query, request.user, view.get_table_data() ) try: config = RequestConfig(request, paginate={"per_page": table.length}) config.configure(table) except ProgrammingError: raise QueryViewDoesNotExistError( "Query view does not exist. Please contact query owner or system " "administrator.") omitted = [result.content_object for result in QueryOmitResult.objects.filter(query=query)] template = loader.get_template('lava_results_app/query_display.html') return HttpResponse(template.render( { 'query': query, 'entity': query.content_type.model, 'conditions': Query.serialize_conditions( query.querycondition_set.all()), 'omitted': omitted, 'query_table': table, 'terms_data': table.prepare_terms_data(view), 'search_data': table.prepare_search_data(view), 'discrete_data': table.prepare_discrete_data(view), 'bread_crumb_trail': BreadCrumbTrail.leading_to( query_display, username=username, name=name), 'context_help': ['lava-queries-charts'], }, request=request) )
def processes(request): open_processes = Process.objects.for_user(request.user).filter(end_date__isnull=True) a_week_ago = datetime.date.today() - datetime.timedelta(days=7) recently_closed_processes = Process.objects.for_user(request.user).filter(end_date__gte=a_week_ago) open_processes_table = ProcessTable(open_processes, prefix="o") recently_closed_processes_table = ProcessEndTable(recently_closed_processes, prefix="c") config = RequestConfig(request) config.configure(open_processes_table) config.configure(recently_closed_processes_table) context = { "open_processes_table": open_processes_table, "recently_closed_processes_table": recently_closed_processes_table, } return render(request, "interview/list_processes.html", context)
def result(request, task_id=None): # read from celery the results # save CSV file task_results = celery_app.AsyncResult(task_id).get() scoring_df = pd.read_csv(StringIO(task_results)) scoring_df = scoring_df.fillna('') scoring_results_table = ScoringTable(scoring_df.to_dict('records')) config = RequestConfig(request) config.paginate = False config.configure(scoring_results_table) return render_to_response( 'review_scoring/result.html', { "scoring_results": scoring_results_table, "task_id": task_id, "scoring_plot": create_html_plot_tooltip(scoring_df) }, context_instance=RequestContext(request))
def search(request): q = request.GET.get("q", "") results = ( Process.objects.for_user(request.user) .filter(Q(candidate__name__icontains=q) | Q(candidate__email__icontains=q)) .distinct() ) search_result = ProcessEndTable(results, prefix="c") config = RequestConfig(request) config.configure(search_result) context = {"title": _('Search result for "{q}"').format(q=q), "table": search_result, "search_query": q} return render(request, "interview/single_table.html", context)
def result(request, task_id=None): # read from celery the results # save CSV file from reviewer_assignment_website import celery_app from StringIO import StringIO task_results = celery_app.AsyncResult(task_id).get() assignment_df = pd.read_csv(StringIO(task_results)) assignment_df = assignment_df.fillna('') reviewer_assignments_table = AssignmentTable( assignment_df.to_dict('records')) config = RequestConfig(request) config.paginate = False config.configure(reviewer_assignments_table) return render_to_response('review_assign/result.html', { "reviewer_assignments": reviewer_assignments_table, "task_id": task_id }, context_instance=RequestContext(request))
def processes_for_source(request, source_id): try: source = Sources.objects.get(id=source_id) except Sources.DoesNotExist: return HttpResponseNotFound() processes = ( Process.objects.for_user(request.user).filter(sources_id=source_id).select_related("candidate", "contract_type") ) processes_table = ProcessEndTable(processes, prefix="c") config = RequestConfig(request) config.configure(processes_table) context = {"title": source.name + " (" + source.category.name + ")", "table": processes_table} return render(request, "interview/single_table.html", context)
def get_context_data(self, **kwargs): """ Configures reward set filters and table information. Returns a context dictionary. """ context = super(RewardMixin, self).get_context_data(**kwargs) context['owner'] = Relation.objects.owned_by(self.request.user) context['owned'] = Reward.objects.owned_by(self.request.user) context['assigned'] = Reward.objects.assigned_to(self.request.user) context['owned_table'] = OwnedRewardTable(context['owned']) context['assigned_table'] = AssignedRewardTable(context['assigned']) requestConfig = RequestConfig(self.request, paginate={ "per_page": 10, }) requestConfig.configure(context['owned_table']) requestConfig.configure(context['assigned_table']) return context
def get_hall_table_by_cinema_id(request, cinema_id): """ Returns all Hall entities as a table with certain Cinema's ID value :param request: :param cinema_id: linked Cinema's ID :return: table with all Hall """ if request.user.is_staff is True: config = RequestConfig(request) content = HallTable(Hall.objects.filter(cinema_id=cinema_id)) config.configure(content) return render(request, 'tables/hall-table.html', { 'table': content, }) else: return render(request, "404.html", {})
def get_poster_table_by_cinema_id(request, cinema_id): """ Returns all Poster entities with certain Cinema's ID value :param request: :param cinema_id: linked Cinema's ID :return: table with all Posters """ if request.user.is_staff is True: config = RequestConfig(request) content = PosterTable(Poster.objects.filter(cinema_id=cinema_id)) config.configure(content) return render(request, 'tables/poster/poster-table-editable.html', { 'table': content, }) else: return render(request, "404.html", {})
def users(req): ''' Show the users page. It is supported to the default User Model (django.contrib.auth.models.User) ''' # Check permission if req.user.is_superuser: pass elif req.user.has_perm('auth.browse_user'): pass else: return HttpResponseForbidden('<h1>403 - Forbidden</h1>') params=dict() params['target']=UserTable(get_user_model().objects.all()) params['btns']=getattr(settings, 'USERS_BTNS', None) rc=RequestConfig(req) rc.configure(params['target']) return render(req, getattr(settings, 'TMPL_USERS', 'webframe/users.html'), params)
def my_subscriptions(request): prefix = "filter_" filter_view = SubscribedFiltersView(request, model=TestRunFilter, table_class=PublicFiltersTable) filters_table = PublicFiltersTable(request.user, filter_view.get_table_data(prefix), prefix=prefix) config = RequestConfig(request) config.configure(filters_table) search_data = filters_table.prepare_search_data(filter_view) discrete_data = filters_table.prepare_discrete_data(filter_view) terms_data = filters_table.prepare_terms_data(filter_view) times_data = filters_table.prepare_times_data(filter_view) prefix = "report_" report_view = SubscribedImageReportView(request, model=ImageReportChart, table_class=UserImageReportTable) report_table = UserImageReportTable(report_view.get_table_data(prefix), prefix=prefix) config = RequestConfig(request) config.configure(report_table) search_data.update(report_table.prepare_search_data(report_view)) discrete_data.update(report_table.prepare_discrete_data(report_view)) terms_data.update(report_table.prepare_terms_data(report_view)) times_data.update(report_table.prepare_times_data(report_view)) template = get_template('dashboard_app/subscribed_list.html') return HttpResponse( template.render( { 'filters_table': filters_table, 'report_table': report_table, "terms_data": terms_data, "search_data": search_data, "times_data": times_data, "discrete_data": discrete_data, 'bread_crumb_trail': BreadCrumbTrail.leading_to(my_subscriptions), }, request=request))
def my_subscriptions(request): prefix = "filter_" filter_view = SubscribedFiltersView(request, model=TestRunFilter, table_class=PublicFiltersTable) filters_table = PublicFiltersTable( request.user, filter_view.get_table_data(prefix), prefix=prefix ) config = RequestConfig(request) config.configure(filters_table) search_data = filters_table.prepare_search_data(filter_view) discrete_data = filters_table.prepare_discrete_data(filter_view) terms_data = filters_table.prepare_terms_data(filter_view) times_data = filters_table.prepare_times_data(filter_view) prefix = "report_" report_view = SubscribedImageReportView(request, model=ImageReportChart, table_class=UserImageReportTable) report_table = UserImageReportTable(report_view.get_table_data(prefix), prefix=prefix) config = RequestConfig(request) config.configure(report_table) search_data.update(report_table.prepare_search_data(report_view)) discrete_data.update(report_table.prepare_discrete_data(report_view)) terms_data.update(report_table.prepare_terms_data(report_view)) times_data.update(report_table.prepare_times_data(report_view)) template = get_template('dashboard_app/subscribed_list.html') return HttpResponse(template.render( { 'filters_table': filters_table, 'report_table': report_table, "terms_data": terms_data, "search_data": search_data, "times_data": times_data, "discrete_data": discrete_data, 'bread_crumb_trail': BreadCrumbTrail.leading_to( my_subscriptions), }, request=request) )
def get_context_data(self, **kwargs): context = super(DisposalList, self).get_context_data(**kwargs) qs = self.get_queryset() config = RequestConfig(self.request, paginate={"per_page": 20}) tablelist ={} num = 1 buildings =['All','QBI','IMB'] #Hard coded but could read from config list for bld in sorted(buildings): pfx = '%d-' % num if (bld == 'All'): table = DisposalTable(qs, prefix=pfx) else: table = DisposalTable(qs.filter(expt_location__building=bld), prefix=pfx) config.configure(table) tablelist[bld] = table num = num+1 context['tablelist'] =tablelist return context
def users(req): ''' Show the users page. It is supported to the default User Model (django.contrib.auth.models.User) ''' # Check permission if req.user.is_superuser: pass elif req.user.has_perm('auth.browse_user'): pass else: return HttpResponseForbidden('<h1>403 - Forbidden</h1>') params = dict() params['target'] = UserTable(get_user_model().objects.all()) params['btns'] = getattr(settings, 'USERS_BTNS', None) rc = RequestConfig(req) rc.configure(params['target']) return render(req, getattr(settings, 'TMPL_USERS', 'webframe/users.html'), params)
def filters_list(request): public_view = PublicFiltersView(request, model=TestRunFilter, table_class=PublicFiltersTable) prefix = "public_" public_filters_table = PublicFiltersTable( request.user, public_view.get_table_data(prefix), prefix=prefix ) config = RequestConfig(request) config.configure(public_filters_table) search_data = public_filters_table.prepare_search_data(public_view) discrete_data = public_filters_table.prepare_discrete_data(public_view) terms_data = public_filters_table.prepare_terms_data(public_view) times_data = public_filters_table.prepare_times_data(public_view) user_filters_table = None if request.user.is_authenticated(): user_view = UserFiltersView(request, model=TestRunFilter, table_class=UserFiltersTable) prefix = "user_" user_filters_table = UserFiltersTable( request.user, user_view.get_table_data(prefix), prefix=prefix ) config.configure(user_filters_table) search_data.update(user_filters_table.prepare_search_data(user_view)) discrete_data.update(user_filters_table.prepare_discrete_data(user_view)) terms_data.update(user_filters_table.prepare_terms_data(user_view)) template = loader.get_template('dashboard_app/filters_list.html') return HttpResponse(template.render( { 'user_filters_table': user_filters_table, 'public_filters_table': public_filters_table, "terms_data": terms_data, "search_data": search_data, "times_data": times_data, "discrete_data": discrete_data, 'bread_crumb_trail': BreadCrumbTrail.leading_to( filters_list), }, request=request) )
def filters_list(request): public_view = PublicFiltersView(request, model=TestRunFilter, table_class=PublicFiltersTable) prefix = "public_" public_filters_table = PublicFiltersTable( request.user, public_view.get_table_data(prefix), prefix=prefix) config = RequestConfig(request) config.configure(public_filters_table) search_data = public_filters_table.prepare_search_data(public_view) discrete_data = public_filters_table.prepare_discrete_data(public_view) terms_data = public_filters_table.prepare_terms_data(public_view) times_data = public_filters_table.prepare_times_data(public_view) user_filters_table = None if request.user.is_authenticated(): user_view = UserFiltersView(request, model=TestRunFilter, table_class=UserFiltersTable) prefix = "user_" user_filters_table = UserFiltersTable(request.user, user_view.get_table_data(prefix), prefix=prefix) config.configure(user_filters_table) search_data.update(user_filters_table.prepare_search_data(user_view)) discrete_data.update( user_filters_table.prepare_discrete_data(user_view)) terms_data.update(user_filters_table.prepare_terms_data(user_view)) template = loader.get_template('dashboard_app/filters_list.html') return HttpResponse( template.render( { 'user_filters_table': user_filters_table, 'public_filters_table': public_filters_table, "terms_data": terms_data, "search_data": search_data, "times_data": times_data, "discrete_data": discrete_data, 'bread_crumb_trail': BreadCrumbTrail.leading_to(filters_list), }, request=request))
def get_context_data(self, **kwargs): """ if meter is present we are showing the meter detail in the same page. """ context_data = super(MeterInfoDetailView, self).get_context_data(**kwargs) config = RequestConfig(self.request) meter = self.object.related_meter if meter: daily_readings = Daily.objects.filter(meter__meters=meter) daily_table = DailyTable(daily_readings, prefix='daily-') config.configure(daily_table) hourly_readings = Hourly.objects.filter(meter__meters=meter) hourly_table = HourlyTable(hourly_readings, prefix='hourly-') config.configure(hourly_table) interval_readings = Reading.objects.filter(meter__meters=meter) interval_table = IntervalTable(interval_readings, prefix='inv-') config.configure(interval_table) context_data.update({ 'daily_table': daily_table, 'hourly_table': hourly_table, 'interval_table': interval_table }) return context_data
def chart_list(request): group_tables = {} terms_data = search_data = discrete_data = {} for group in ChartGroup.objects.all(): if group.chart_set.count(): prefix = "group_%s_" % group.id group_view = GroupChartView( request, group, model=Chart, table_class=GroupChartTable ) table = GroupChartTable( group_view.get_table_data(prefix), request=request, prefix=prefix ) search_data.update(table.prepare_search_data(group_view)) discrete_data.update(table.prepare_discrete_data(group_view)) terms_data.update(table.prepare_terms_data(group_view)) group_tables[group.name] = table config = RequestConfig(request, paginate={"per_page": table.length}) config.configure(table) prefix = "other_" other_view = OtherChartView(request, model=Chart, table_class=OtherChartTable) other_chart_table = OtherChartTable( other_view.get_table_data(prefix), request=request, prefix=prefix ) config = RequestConfig(request, paginate={"per_page": other_chart_table.length}) config.configure(other_chart_table) search_data.update(other_chart_table.prepare_search_data(other_view)) discrete_data.update(other_chart_table.prepare_discrete_data(other_view)) terms_data.update(other_chart_table.prepare_terms_data(other_view)) if request.user.is_authenticated: prefix = "user_" view = UserChartView(request, model=Chart, table_class=UserChartTable) user_chart_table = UserChartTable( view.get_table_data(prefix), request=request, prefix=prefix ) config = RequestConfig(request, paginate={"per_page": user_chart_table.length}) config.configure(user_chart_table) search_data.update(user_chart_table.prepare_search_data(view)) discrete_data.update(user_chart_table.prepare_discrete_data(view)) terms_data.update(user_chart_table.prepare_terms_data(view)) else: user_chart_table = None template = loader.get_template("lava_results_app/chart_list.html") return HttpResponse( template.render( { "user_chart_table": user_chart_table, "other_chart_table": other_chart_table, "search_data": search_data, "discrete_data": discrete_data, "terms_data": terms_data, "group_tables": group_tables, "bread_crumb_trail": BreadCrumbTrail.leading_to(chart_list), "context_help": ["lava-queries-charts"], }, request=request, ) )
def get_context_data(self, **kwargs): """ if meter is present we are showing the meter detail in the same page. """ context_data = super(MeterInfoDetailView, self ).get_context_data(**kwargs) config = RequestConfig(self.request) meter = self.object.related_meter if meter: daily_readings = Daily.objects.filter(meter__meters=meter) daily_table = DailyTable(daily_readings, prefix='daily-') config.configure(daily_table) hourly_readings = Hourly.objects.filter(meter__meters=meter) hourly_table = HourlyTable(hourly_readings, prefix='hourly-') config.configure(hourly_table) interval_readings = Reading.objects.filter(meter__meters=meter) interval_table = IntervalTable(interval_readings, prefix='inv-') config.configure(interval_table) context_data.update({'daily_table': daily_table, 'hourly_table': hourly_table, 'interval_table': interval_table}) return context_data
def query_custom(request): content_type = Query.get_content_type(request.GET.get("entity")) if content_type.model_class() not in QueryCondition.RELATION_MAP: raise InvalidContentTypeError( "Wrong table name in entity param. Please refer to query docs.") view = QueryCustomResultView( content_type=content_type, conditions=Query.parse_conditions(content_type, request.GET.get("conditions")), request=request, model=content_type.model_class(), table_class=QUERY_CONTENT_TYPE_TABLE[content_type.model_class()] ) try: table = QUERY_CONTENT_TYPE_TABLE[content_type.model_class()]( view.get_table_data() ) except FieldError: raise InvalidConditionsError("Conditions URL incorrect: Field does " "not exist. Please refer to query docs.") config = RequestConfig(request, paginate={"per_page": table.length}) config.configure(table) return render_to_response( 'lava_results_app/query_custom.html', { 'query_table': table, 'terms_data': table.prepare_terms_data(view), 'search_data': table.prepare_search_data(view), 'discrete_data': table.prepare_discrete_data(view), 'bread_crumb_trail': BreadCrumbTrail.leading_to(query_custom), 'context_help': BreadCrumbTrail.leading_to(query_list), }, RequestContext(request) )
def query_list(request): group_tables = {} terms_data = search_data = discrete_data = {} for group in QueryGroup.objects.all(): if group.query_set.count(): prefix = "group_%s_" % group.id group_view = GroupQueryView(request, group, model=Query, table_class=GroupQueryTable) table = GroupQueryTable(group_view.get_table_data(prefix), prefix=prefix) search_data.update(table.prepare_search_data(group_view)) discrete_data.update(table.prepare_discrete_data(group_view)) terms_data.update(table.prepare_terms_data(group_view)) group_tables[group.name] = table config = RequestConfig(request, paginate={"per_page": table.length}) config.configure(table) prefix = "other_" other_view = OtherQueryView(request, model=Query, table_class=OtherQueryTable) other_query_table = OtherQueryTable(other_view.get_table_data(prefix), prefix=prefix) config = RequestConfig(request, paginate={"per_page": other_query_table.length}) config.configure(other_query_table) search_data.update(other_query_table.prepare_search_data(other_view)) discrete_data.update(other_query_table.prepare_discrete_data(other_view)) terms_data.update(other_query_table.prepare_terms_data(other_view)) prefix = "user_" view = UserQueryView(request, model=Query, table_class=UserQueryTable) user_query_table = UserQueryTable(view.get_table_data(prefix), prefix=prefix) config = RequestConfig(request, paginate={"per_page": user_query_table.length}) config.configure(user_query_table) search_data.update(user_query_table.prepare_search_data(view)) discrete_data.update(user_query_table.prepare_discrete_data(view)) terms_data.update(user_query_table.prepare_terms_data(view)) template = loader.get_template('lava_results_app/query_list.html') return HttpResponse( template.render( { 'user_query_table': user_query_table, 'other_query_table': other_query_table, 'search_data': search_data, "discrete_data": discrete_data, 'terms_data': terms_data, 'group_tables': group_tables, 'bread_crumb_trail': BreadCrumbTrail.leading_to(query_list), 'context_help': ['lava-queries-charts'], }, request=request))
def prefs(req, user=None): ''' Show the preference page of the specified user. If requesting to show user that is not current session, the superuser permission are required. ''' if user == '_': return redirect('webframe:prefs', user=req.user) if user == None: user = req.user.username if user != req.user.username and not req.user.is_superuser: if req.user.username != user: return HttpResponseForbidden('<h1>403-Forbidden</h1>') user = getObj(get_user_model(), username=user) if req.method == 'POST': newPwd = req.POST.get('newPwd', None) if newPwd and newPwd == req.POST.get('rePwd', None): user.set_password(newPwd) user.save() auth_logout(req) return redirect('webframe:prefs', user=user) params = dict() params['preference'] = PreferenceTable( Preference.objects.filter(owner=req.user, parent__isnull=True)) params['config'] = PreferenceTable( Preference.objects.filter(owner__isnull=True, parent__isnull=True)) rc = RequestConfig(req) rc.configure(params['preference']) rc.configure(params['config']) params['currentuser'] = user if req.user.has_perm('webframe.add_config') or req.user.has_perm( 'webframe.change.config'): m = hashlib.md5() m.update(user.username.encode('utf-8')) m.update(CONFIG_KEY.encode('utf-8')) params['config_key'] = m.hexdigest() return render( req, getattr(settings, 'TMPL_PREFERENCES', 'webframe/preferences.html'), params)
def city_list(request): """ The Controller prepares tables for displaying a list of cities as tables. For authorized users only. The table uses pagination of 5 records per page. :param request: HttpRequest object :return: HttpResponse object returned as a result of calling render() function with passed arguments (html document with city tables) """ config = RequestConfig(request, paginate={"per_page": 5}) continents = Continent.objects.all().order_by('name') tables = [ CityTable(City.objects.filter(continent=continent), prefix=continent.name) for continent in continents ] for table in tables: config.configure(table) return render(request, 'cities/city_list.html', { 'tables': tables, })
def chart_list(request): group_tables = {} terms_data = search_data = discrete_data = {} for group in ChartGroup.objects.all(): if group.chart_set.count(): prefix = "group_%s_" % group.id group_view = GroupChartView(request, group, model=Chart, table_class=GroupChartTable) table = GroupChartTable(group_view.get_table_data(prefix), prefix=prefix) search_data.update(table.prepare_search_data(group_view)) discrete_data.update(table.prepare_discrete_data(group_view)) terms_data.update(table.prepare_terms_data(group_view)) group_tables[group.name] = table config = RequestConfig(request, paginate={"per_page": table.length}) config.configure(table) prefix = "other_" other_view = OtherChartView(request, model=Chart, table_class=OtherChartTable) other_chart_table = OtherChartTable(other_view.get_table_data(prefix), prefix=prefix) config = RequestConfig(request, paginate={"per_page": other_chart_table.length}) config.configure(other_chart_table) search_data.update(other_chart_table.prepare_search_data(other_view)) discrete_data.update(other_chart_table.prepare_discrete_data(other_view)) terms_data.update(other_chart_table.prepare_terms_data(other_view)) if request.user.is_authenticated(): prefix = "user_" view = UserChartView(request, model=Chart, table_class=UserChartTable) user_chart_table = UserChartTable(view.get_table_data(prefix), prefix=prefix) config = RequestConfig(request, paginate={"per_page": user_chart_table.length}) config.configure(user_chart_table) search_data.update(user_chart_table.prepare_search_data(view)) discrete_data.update(user_chart_table.prepare_discrete_data(view)) terms_data.update(user_chart_table.prepare_terms_data(view)) else: user_chart_table = None template = loader.get_template('lava_results_app/chart_list.html') return HttpResponse(template.render( { 'user_chart_table': user_chart_table, 'other_chart_table': other_chart_table, 'search_data': search_data, "discrete_data": discrete_data, 'terms_data': terms_data, 'group_tables': group_tables, 'bread_crumb_trail': BreadCrumbTrail.leading_to(chart_list), 'context_help': ['lava-queries-charts'], }, request=request) )
def query_display(request, username, name): query = get_object_or_404(Query, owner__username=username, name=name) view = QueryResultView( query=query, request=request, model=query.content_type.model_class(), table_class=QUERY_CONTENT_TYPE_TABLE[query.content_type.model_class()] ) table = QUERY_CONTENT_TYPE_TABLE[query.content_type.model_class()]( view.get_table_data() ) try: config = RequestConfig(request, paginate={"per_page": table.length}) config.configure(table) except ProgrammingError: raise QueryViewDoesNotExistError( "Query view does not exist. Please contact query owner or system " "administrator.") return render_to_response( 'lava_results_app/query_display.html', { 'query': query, 'entity': query.content_type.model, 'conditions': query.serialize_conditions(), 'query_table': table, 'terms_data': table.prepare_terms_data(view), 'search_data': table.prepare_search_data(view), 'discrete_data': table.prepare_discrete_data(view), 'bread_crumb_trail': BreadCrumbTrail.leading_to( query_display, username=username, name=name), 'context_help': BreadCrumbTrail.leading_to(query_list), }, RequestContext(request) )
def query_list(request): group_tables = {} terms_data = search_data = discrete_data = {} for group in QueryGroup.objects.all(): if group.query_set.count(): prefix = "group_%s_" % group.id group_view = GroupQueryView(request, group, model=Query, table_class=GroupQueryTable) table = GroupQueryTable(group_view.get_table_data(prefix), prefix=prefix) search_data.update(table.prepare_search_data(group_view)) discrete_data.update(table.prepare_discrete_data(group_view)) terms_data.update(table.prepare_terms_data(group_view)) group_tables[group.name] = table config = RequestConfig(request, paginate={"per_page": table.length}) config.configure(table) prefix = "other_" other_view = OtherQueryView(request, model=Query, table_class=OtherQueryTable) other_query_table = OtherQueryTable(other_view.get_table_data(prefix), prefix=prefix) config = RequestConfig(request, paginate={"per_page": other_query_table.length}) config.configure(other_query_table) search_data.update(other_query_table.prepare_search_data(other_view)) discrete_data.update(other_query_table.prepare_discrete_data(other_view)) terms_data.update(other_query_table.prepare_terms_data(other_view)) if request.user.is_authenticated(): prefix = "user_" view = UserQueryView(request, model=Query, table_class=UserQueryTable) user_query_table = UserQueryTable(view.get_table_data(prefix), prefix=prefix) config = RequestConfig(request, paginate={"per_page": user_query_table.length}) config.configure(user_query_table) search_data.update(user_query_table.prepare_search_data(view)) discrete_data.update(user_query_table.prepare_discrete_data(view)) terms_data.update(user_query_table.prepare_terms_data(view)) else: user_query_table = None return render_to_response( 'lava_results_app/query_list.html', { 'user_query_table': user_query_table, 'other_query_table': other_query_table, 'search_data': search_data, "discrete_data": discrete_data, 'terms_data': terms_data, 'group_tables': group_tables, 'bread_crumb_trail': BreadCrumbTrail.leading_to(query_list), 'context_help': BreadCrumbTrail.leading_to(query_list), }, RequestContext(request) )
def guide(request, *args): """provides all guide content in 5 tables """ print request channels_filtered=request.GET.getlist('channels') now = datetime.today() hour=now.hour minutes=now.minute if hour>12: hour=hour-12 if minutes>30: startmin=30 endmin=60-minutes timedeltastart=minutes-startmin else: startmin="00" endmin=30-minutes timedeltastart=minutes-int(startmin) timetostart=("%s:%s"%(hour,startmin)) hour_list=[timetostart,hour,hour+1] start_times=[] end_times=[] increment=30 howmanytables=4 list_of_displaytimes=[] for a in xrange(0,howmanytables): start_times.append((datetime.now()-timedelta(minutes=timedeltastart+5-increment*a)).time()) end_times.append((datetime.now()+timedelta(minutes=endmin-1+increment*(a))).time()) displaytime=(datetime.now()-timedelta(minutes=timedeltastart-increment*a)).time() list_of_displaytimes.append(displaytime) config = RequestConfig(request,paginate={"per_page":25}) table1= TitlesTable(Titles.objects.filter(time__lt=(start_times[0]), time__gte=(datetime.now()-timedelta(minutes=120+5)).time()), prefix="1-") table2 = TitlesTable(Titles.objects.filter(time__gte=(start_times[0]), time__lt=(end_times[0])), prefix="2-") table3= TitlesTable(Titles.objects.filter(time__gte=(start_times[1]), time__lt=(end_times[1])), prefix="3-") table4 = TitlesTable(Titles.objects.filter(time__gte=(start_times[2]), time__lt=(end_times[2])), prefix="4-") table5 = TitlesTable(Titles.objects.filter(time__gte=(start_times[3]), time__lt=(end_times[3])), prefix="5-") config.configure(table1) config.configure(table2) config.configure(table3) config.configure(table4) config.configure(table5) return render(request, 'guide.html', {'table1':table1, 'table2':table2, 'table3':table3, 'table4': table4, 'table5':table5, 'current_date':now, 'list_of_hours':list_of_displaytimes,'list_of_endtimes':end_times})
def get_context_data(self, **kwargs): """ Show tables for each readings. """ context = super(MeterDetailView, self).get_context_data(**kwargs) config = RequestConfig(self.request) meter = self.object daily_readings = Daily.objects.filter(meter__meters=meter) daily_table = DailyTable(daily_readings, prefix='daily-') config.configure(daily_table) hourly_readings = Hourly.objects.filter(meter__meters=meter) hourly_table = HourlyTable(hourly_readings, prefix='hourly-') config.configure(hourly_table) interval_readings = Reading.objects.filter(meter__meters=meter).order_by('nmsrealtime') interval_table = IntervalTable(interval_readings, prefix='inv-') config.configure(interval_table) context.update({'daily_table': daily_table, 'hourly_table': hourly_table, 'interval_table': interval_table}) return context
def guide_filtered(request): """provides guide content which is filtered by channel, showtype and cookies """ token=request.COOKIES['csrftoken'] print "Cookies!!!!!!!!!!!!!!!!!!!!!" print request.COOKIES channels_list=["HBO","MAX","SHO","Starz","Encore"] channels_filtered=request.GET.getlist('channels') print channels_list type_filtered=request.GET.get('type') #switch the value of type filtered to the other so that it can properly exclude the opposite value if type_filtered=="Tv": type_filtered="Movie" elif type_filtered=="Movie": type_filtered="Tv" for a in channels_filtered: channels_list.pop(channels_list.index(a)) print 'DATETIME' print datetime print 'Timesec' print 'converted time' #now = datetime.fromtimestamp(time_sec).today() now = datetime.today() hour=now.hour minutes=now.minute if minutes>30: startmin=30 endmin=60-minutes timedeltastart=minutes-startmin else: startmin="00" endmin=30-minutes timedeltastart=minutes-int(startmin) timetostart=("%s:%s"%(hour,startmin)) hour_list=[timetostart,hour,hour+1] start_times=[] end_times=[] increment=30 howmanytables=4 list_of_displaytimes=[] for a in xrange(0,howmanytables): start_times.append((datetime.now()-timedelta(minutes=timedeltastart+5-increment*a)).time()) end_times.append((datetime.now()+timedelta(minutes=endmin-1+increment*(a))).time()) list_of_displaytimes.append((datetime.now()-timedelta(minutes=timedeltastart-increment*a)).time()) #filters out any channel that was passed in the Get request as checkmarked if channels_filtered: ob_list_channelsremoved = Titles.objects.exclude(reduce(lambda x, y: x | y, [Q(channel__contains=word) for word in channels_filtered])) else: ob_list_channelsremoved=Titles.objects.all() if type_filtered: ob_list_channelsremoved = ob_list_channelsremoved.exclude(showtype__contains=type_filtered) config = RequestConfig(request,paginate={"per_page":25}) #following code is used to allow for comparison in a 24hour format, without dates. Does so by checking to see if it is near midnight. time_back=datetime.now()-timedelta(minutes=60+5) time_back_minutes=time_back.minute time_back_hour=time_back.hour difference_in_hours=hour-time_back_hour if difference_in_hours<0 and start_times[0].hour==23: print "doing code inside differnce of hours and 23" filtered_object=ob_list_channelsremoved.filter(time__gte=(datetime.now()-timedelta(minutes=60+5)).time(),csrftoken=token) filtered_objects=filtered_object elif difference_in_hours<0 and start_times[0].hour!=23: print "doing code inside differnce of hours and not 23" filtered_object=ob_list_channelsremoved.filter(time__gte=(datetime.now()-timedelta(minutes=60+5)).time(),csrftoken=token) filtered_object_one=ob_list_channelsremoved.filter(time__lt=(start_times[0]),csrftoken=token) filtered_objects=filtered_object|filtered_object_one else: print 'doing code in else' filtered_objects='' filtered_objects=ob_list_channelsremoved.filter(time__gte=(datetime.now()-timedelta(minutes=60+5)),time__lt=(start_times[0]),csrftoken=token) #used to go through each list and determine if a new day has occurred, if so it runs a query for it else runs a regular query tables_list=[] for a in xrange(0,len(start_times)): start_end_difference=start_times[a].hour-end_times[a].hour if start_end_difference>0: print "problem with table %s"%a filtered_object=ob_list_channelsremoved.filter(time__gte=(start_times[a]),csrftoken=token) filtered_object_one=ob_list_channelsremoved.filter(time__lt=(end_times[a]),csrftoken=token) adjusting_midnight=filtered_object|filtered_object_one tables_list.append(adjusting_midnight) else: print "no problem with table %s"%a adjusting_midnight = ob_list_channelsremoved.filter(time__gte=(start_times[a]), time__lt=(end_times[a]),csrftoken=token) tables_list.append(adjusting_midnight) table1= TitlesTable(filtered_objects,prefix="1-") titles_tables=[] for a in xrange(0,len(tables_list)): tables=TitlesTable(tables_list[a], prefix='%s-'%a) titles_tables.append(tables) config.configure(table1) config.configure(titles_tables[0]) config.configure(titles_tables[1]) config.configure(titles_tables[2]) config.configure(titles_tables[3]) return render(request, 'guide.html', {'table1':table1, 'table2':titles_tables[0], 'table3':titles_tables[1], 'table4': titles_tables[2], 'table5':titles_tables[3], 'current_date':now, 'list_of_hours':list_of_displaytimes,'list_of_endtimes':end_times})