Пример #1
0
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
Пример #2
0
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),
    )
Пример #3
0
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)
Пример #4
0
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,})
Пример #5
0
    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
Пример #6
0
 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)
Пример #7
0
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 })
Пример #8
0
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})
Пример #9
0
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() })
Пример #10
0
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)
    )
Пример #11
0
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)
    )
Пример #12
0
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)
    )
Пример #13
0
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'))
Пример #14
0
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))
Пример #15
0
    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
Пример #16
0
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)
    )
Пример #17
0
    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
Пример #18
0
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)
Пример #19
0
 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
Пример #20
0
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)
    )
Пример #21
0
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)
    )
Пример #22
0
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)
    )
Пример #23
0
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})
Пример #24
0
 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
Пример #25
0
 def get_context_data(self, **kwargs):
     """
     Configures relation set filters and table information.
     Returns a context dictionary.
     """
     context = super(RelationMixin, self).get_context_data(**kwargs)
     context['owned'] = Relation.objects.owned_by(self.request.user)
     context['assigned'] = Relation.objects.assigned_to(self.request.user)
     context['proposed'] = Relation.objects.proposed_by(self.request.user)
     context['pending'] = Relation.objects.pending_for(self.request.user)
     context['owned_table'] = OwnedRelationTable(context['owned'])
     context['assigned_table'] = AssignedRelationTable(context['assigned'])
     context['proposed_table'] = ProposedRelationTable(context['proposed'])
     context['pending_table'] = PendingRelationTable(context['pending'])
     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'])
     return context
Пример #26
0
def standard_list(request):
    icontains_fields = [
        'inventory_id', 'molecule__name', 'molecule__sum_formula',
        'molecule__exact_mass', 'vendor', 'vendor_cat', 'molecule__pubchem_id'
    ]
    search_string = request.GET.get('search', None)
    qs = Standard.objects.all()
    if search_string:
        queries = [
            Q(**{field + '__icontains': search_string})
            for field in icontains_fields
        ]
        search_query = queries.pop()
        for q in queries:
            search_query |= q
        qs = qs.filter(search_query)
    table = StandardTable(qs,
                          attrs={
                              'id': 'molecule_list',
                              'class': 'table table-striped'
                          })
    RequestConfig(request).configure(table)
    return render(request, "mcf_standards_browse/mcf_standard_list.html",
                  {'standard_list': table})
Пример #27
0
    def get_extra_context(self, request, instance):

        # Clusters
        clusters = (
            Cluster.objects.restrict(request.user, "view")
            .filter(group=instance)
            .prefetch_related("type", "site", "tenant")
        ).annotate(
            device_count=count_related(Device, "cluster"),
            vm_count=count_related(VirtualMachine, "cluster"),
        )

        cluster_table = tables.ClusterTable(clusters)
        cluster_table.columns.hide("group")

        paginate = {
            "paginator_class": EnhancedPaginator,
            "per_page": get_paginate_count(request),
        }
        RequestConfig(request, paginate).configure(cluster_table)

        return {
            "cluster_table": cluster_table,
        }
Пример #28
0
def workstation_schedule(request, date: str):
    monday = datetime.strptime(date, '%Y-%m-%d')
    if monday > (datetime.today() + timedelta(days=28) +
                 relativedelta(day=31)):
        message = _('Future schedule is unavailable')
        messages.info(request, message)
        return redirect('workstation_schedule',
                        date=(monday - timedelta(days=7)).strftime('%Y-%m-%d'))
    try:
        first_monday = Userweek.objects.all().order_by(
            'monday_date')[0].monday_date
    except IndexError:
        isotoday = datetime.today().isocalendar()
        Userweek.objects.get_or_create(employee=request.user,
                                       year=isotoday[0],
                                       week=isotoday[1])
        first_monday = Userweek.objects.all().order_by(
            'monday_date')[0].monday_date
    if monday.date() < first_monday:
        message = _('Weeks before databease creation are unavailable')
        messages.info(request, message)
        return redirect('workstation_schedule',
                        date=(monday + timedelta(days=7)).strftime('%Y-%m-%d'))
    date_range, table = views_processing.get_schedule_week_table(monday)
    RequestConfig(request).configure(table)
    monday = monday + timedelta(weeks=1)
    next_date = monday.strftime('%Y-%m-%d')
    monday = monday - timedelta(days=14)
    previous_date = monday.strftime('%Y-%m-%d')
    return render(
        request, 'spaceplanner/workstation_schedule.html', {
            'table': table,
            'date_range': date_range,
            'next_date': next_date,
            'previous_date': previous_date
        })
Пример #29
0
def default(request):
    params = StandardRequestParams.load_from_request(request)

    aggregation = aggregations.asset_rollup(
        time_range=params.time_range(),
        supply_cols=params.supply_components,
        demand_calculation_config=DemandCalculationConfig(rollup_fn=params.rollup_fn),
    )

    cleaned_aggregation = [
        rollup
        for rollup in list(aggregation.values())
        if not all([rollup._value_at(col) == 0 for col in AggColumn.all()])
    ]

    table = aggregations.AggregationTable(cleaned_aggregation)
    RequestConfig(request).configure(table)
    context = {
        "aggregations": table,
        "days_in_view": dc.Period(params.start_date, params.end_date)
        .inclusive_length()
        .days,
    }
    return render(request, "dashboard.html", context)
Пример #30
0
def suite(request, job, pk):
    job = get_restricted_job(request.user, pk=job, request=request)
    test_suite = get_object_or_404(TestSuite, name=pk, job=job)
    data = SuiteView(request, model=TestCase, table_class=SuiteTable)
    suite_table = SuiteTable(data.get_table_data().filter(suite=test_suite),
                             request=request)
    RequestConfig(request, paginate={
        "per_page": suite_table.length
    }).configure(suite_table)
    template = loader.get_template("lava_results_app/suite.html")
    return HttpResponse(
        template.render(
            {
                "bread_crumb_trail":
                BreadCrumbTrail.leading_to(suite, pk=pk, job=job.id),
                "job":
                job,
                "job_link":
                pklink(job),
                "testsuite_content_type_id":
                ContentType.objects.get_for_model(TestSuite).id,
                "suite_name":
                pk,
                "suite_id":
                test_suite.id,
                "suite_table":
                suite_table,
                "bug_links":
                BugLink.objects.filter(
                    object_id=test_suite.id,
                    content_type_id=ContentType.objects.get_for_model(
                        TestSuite).id,
                ),
            },
            request=request,
        ))
Пример #31
0
def bundle_list(request, pathname):
    """
    List of bundles in a specified bundle stream.
    """
    bundle_stream = get_restricted_object(BundleStream,
                                          lambda bundle_stream: bundle_stream,
                                          request.user,
                                          pathname=pathname)
    data = BundleView(request,
                      bundle_stream,
                      model=Bundle,
                      table_class=BundleTable)
    table = BundleTable(data.get_table_data())
    RequestConfig(request, paginate={
        "per_page": table.length
    }).configure(table)
    template = get_template("dashboard_app/bundle_list.html")
    return HttpResponse(
        template.render(
            {
                'bundle_list':
                table,
                'bread_crumb_trail':
                BreadCrumbTrail.leading_to(bundle_list, pathname=pathname),
                "terms_data":
                table.prepare_terms_data(data),
                "search_data":
                table.prepare_search_data(data),
                "discrete_data":
                table.prepare_discrete_data(data),
                "times_data":
                table.prepare_times_data(data),
                "bundle_stream":
                bundle_stream,
            },
            request=request))
Пример #32
0
def details(request, organization, project_id):
    organization = get_object_or_404(Organization, name=organization)
    project = get_object_or_404(Project, id=project_id)

    setting, _ = Setting.objects.get_or_create(user=request.user)
    timezone = pytz.timezone(str(setting.timezone))

    if not project.is_member(request.user):
        return HttpResponseForbidden()

    tl_activate(setting.locale)
    tz_activate(timezone)

    members = set(set(project.admins.all()) | set(project.editors.all()))

    recent_query = project.timerecord_set.order_by('-end_time')[:5]
    recent_changes = RecentRecordTable(recent_query, request=request)
    RequestConfig(request, paginate=False).configure(recent_changes)

    context = dict(organization=organization,
                   project=project,
                   members=members,
                   recent_changes=recent_changes)
    return render(request, 'tracker/project/details.html', context)
Пример #33
0
def landscape_query(request, landscape_name, query_name, surveys=[]):
    # username = None
    mymodel = apps.get_model('bns', query_name)

    class myTable(tables.Table):
        name = mymodel.table_name

        class Meta:
            model = mymodel
            template_name = 'bootstrap.html'

    class myFilter(django_filters.FilterSet):
        class Meta:
            model = mymodel
            fields = mymodel.filter_fields

    queryset = mymodel.objects.filter(landscape=landscape_name)

    if not request.user.is_superuser:
        if not 'landscape' in query_name.lower():
            queryset = queryset.filter(dataset_uuid_id__in=surveys)

    filter = myFilter(request.GET, queryset=queryset)

    table = myTable(filter.qs)
    RequestConfig(request).configure(table)

    export_format = request.GET.get('_export', None)
    if TableExport.is_valid_format(export_format):
        exporter = TableExport(export_format, table)
        return exporter.response('{}.{}'.format(mymodel.table_name, export_format))

    table.paginate(page=request.GET.get('page', 1), per_page=request.GET.get('per_page', 10))
    table.export_formats = ['csv', 'xls', 'json', 'tsv']

    return render(request, 'bns_landscape_query.html', {'table': table, 'filter': filter, 'landscape_name': landscape_name})
Пример #34
0
def ajax_add_product(request, pk, dk): #add product in OrderItem cart
    instance = get_object_or_404(Order, id=pk)
    product = get_object_or_404(Product, id=dk)
    order_item, created = OrderItem.objects.get_or_create(order=instance, product=product)
    if created:
        order_item.qty = 1
        order_item.price = product.price
        # order_item.discount_price = product.discount_value
    else:
        order_item.qty += 1
    order_item.save()
    product.qty -= 1
    product.save()
    instance.refresh_from_db()
    order_items = OrderItemTable(instance.order_items.all())
    RequestConfig(request).configure(order_items)
    data = dict()
    data['result'] = render_to_string(template_name='include/order_container.html',
                                      request=request,
                                      context={'instance': instance,
                                               'order_items': order_items
                                               }
                                    )
    return JsonResponse(data)
    def get_context_data(self, **kwargs):
        context = super(RelatorioProdutosView, self).get_context_data(**kwargs)
        context['title_complete'] = 'Relatório de Produtos'
        context['mais_vendidos'] = self.model.objects.order_by(
            '-quantidade_vendida')[:10]
        context['mais_vendidos'] = reversed(context['mais_vendidos'])

        context['menos_vendidos'] = self.model.objects.order_by(
            'quantidade_vendida')[:10]
        context['menos_vendidos'] = reversed(context['menos_vendidos'])

        table = self.table_class(self.model.objects.all())
        table.paginate(page=self.request.GET.get('page', 1), per_page=15)
        table.exclude = ('lancamento_ptr')

        context['table'] = table
        RequestConfig(self.request).configure(table)  #ordena

        export_format = self.request.GET.get('_export', None)
        if TableExport.is_valid_format(export_format):
            exporter = TableExport(export_format, table)
            return exporter.response('File_Name.{}'.format(export_format))

        return context
Пример #36
0
    def get(self, request, slug):

        tag = get_object_or_404(Tag, slug=slug)
        tagged_items = TaggedItem.objects.filter(
            tag=tag
        ).select_related(
            'content_type'
        ).prefetch_related(
            'content_object'
        )

        # Generate a table of all items tagged with this Tag
        items_table = TaggedItemTable(tagged_items)
        paginate = {
            'paginator_class': EnhancedPaginator,
            'per_page': request.GET.get('per_page', settings.PAGINATE_COUNT)
        }
        RequestConfig(request, paginate).configure(items_table)

        return render(request, 'extras/tag.html', {
            'tag': tag,
            'items_count': tagged_items.count(),
            'items_table': items_table,
        })
Пример #37
0
def lessons_day(
    request: HttpRequest,
    year: Optional[int] = None,
    month: Optional[int] = None,
    day: Optional[int] = None,
) -> HttpResponse:
    """View all lessons taking place on a specified day."""
    context = {}

    if day:
        wanted_day = timezone.datetime(year=year, month=month, day=day).date()
        wanted_day = TimePeriod.get_next_relevant_day(wanted_day)
    else:
        wanted_day = TimePeriod.get_next_relevant_day(timezone.now().date(),
                                                      datetime.now().time())

    # Get lessons
    lesson_periods = LessonPeriod.objects.on_day(wanted_day)

    # Build table
    lessons_table = LessonsTable(lesson_periods.all())
    RequestConfig(request).configure(lessons_table)

    context["lessons_table"] = lessons_table
    context["day"] = wanted_day
    context["lesson_periods"] = lesson_periods

    context["datepicker"] = {
        "date": date_unix(wanted_day),
        "dest": reverse("lessons_day"),
    }

    context["url_prev"], context["url_next"] = TimePeriod.get_prev_next_by_day(
        wanted_day, "lessons_day_by_date")

    return render(request, "chronos/lessons_day.html", context)
Пример #38
0
def home(request):
    current_projects = Project.objects.exclude(
        end_date__lte=datetime.date.today())
    res = []

    for proj in current_projects:
        dict = {}
        dict['project'] = proj.name
        payments = Payment.objects.filter(project_id=proj,
                                          payment_from="CLIENT")
        total_payment = 0
        for payment in payments:
            total_payment += payment.amount
        expenses = Expense.objects.filter(project_id=proj)
        total_expense = 0
        for exp in expenses:
            total_expense += exp.amount
        employees = Employee.objects.all()
        lab_amount = 0
        for emp in employees:
            a = Attendance.objects.filter(project=proj, employee=emp)
            if a.exists():
                shifts = (a.aggregate(total=Sum('shift'))['total'] or 0) / 2
                lab_amount += shifts * emp.salary
        dict['total_payment'] = total_payment
        dict['total_cost'] = total_expense + lab_amount
        thresold_payment = dict['total_cost'] * 0.35 + dict['total_cost']
        thresold_balance = thresold_payment - total_payment
        dict['thresold_payment'] = thresold_payment
        dict['thresold_balance'] = thresold_balance
        if (total_expense > 0 and thresold_payment > total_payment):
            res.append(dict)
    table = DefaultersTable(res)
    RequestConfig(request, paginate={"per_page": 15}).configure(table)
    context = {'table': table}
    return render(request, "home.html", context)
def bundle_stream_list(request):
    """
    List of bundle streams.
    """
    data = BundleStreamView(request, model=BundleStream, table_class=BundleStreamTable)
    table = BundleStreamTable(data.get_table_data())
    RequestConfig(request, paginate={"per_page": table.length}).configure(table)
    return render_to_response(
        'dashboard_app/bundle_stream_list.html', {
            'bread_crumb_trail': BreadCrumbTrail.leading_to(
                bundle_stream_list),
            "bundle_stream_table": table,
            "terms_data": table.prepare_terms_data(data),
            "search_data": table.prepare_search_data(data),
            "discrete_data": table.prepare_discrete_data(data),
            'has_personal_streams': (
                request.user.is_authenticated() and
                BundleStream.objects.filter(user=request.user).count() > 0),
            'has_team_streams': (
                request.user.is_authenticated() and
                BundleStream.objects.filter(
                    group__in=request.user.groups.all()).count() > 0),
        }, RequestContext(request)
    )
Пример #40
0
def testjob(request, job):
    job = get_restricted_job(request.user, pk=job, request=request)
    data = ResultsView(request, model=TestSuite, table_class=TestJobResultsTable)
    suite_table = TestJobResultsTable(
        data.get_table_data().filter(job=job), request=request
    )
    failed_definitions = []
    yaml_dict = OrderedDict()

    testdata = TestData.objects.filter(testjob=job).first()
    if testdata:
        for data in testdata.attributes.all().order_by("name"):
            yaml_dict[str(data.name)] = str(data.value)

    RequestConfig(request, paginate={"per_page": suite_table.length}).configure(
        suite_table
    )
    template = loader.get_template("lava_results_app/job.html")
    return HttpResponse(
        template.render(
            {
                "bread_crumb_trail": BreadCrumbTrail.leading_to(testjob, job=job.id),
                "job": job,
                "job_link": pklink(job),
                "suite_table": suite_table,
                "metadata": yaml_dict,
                "condition_choices": simplejson.dumps(
                    QueryCondition.get_condition_choices(job)
                ),
                "available_content_types": simplejson.dumps(
                    QueryCondition.get_similar_job_content_types()
                ),
            },
            request=request,
        )
    )
def bundle_detail(request, pathname, content_sha1):
    """
    Detail about a bundle from a particular stream
    """
    bundle_stream = get_object_or_404(BundleStream, pathname=pathname)
    bundle = get_object_or_404(Bundle, bundle_stream=bundle_stream, content_sha1=content_sha1)
    try:
        next_bundle = Bundle.objects.filter(bundle_stream=bundle_stream, id__lt=bundle.id)[0]
    except IndexError:
        next_bundle = None
    try:
        previous_bundle = Bundle.objects.filter(bundle_stream=bundle_stream, id__gt=bundle.id).reverse()[0]
    except IndexError:
        previous_bundle = None
    view = BundleDetailView(request, pathname=pathname, content_sha1=content_sha1, model=TestRun, table_class=BundleDetailTable)
    bundle_table = BundleDetailTable(view.get_table_data())
    RequestConfig(request, paginate={"per_page": bundle_table.length}).configure(bundle_table)
    return render_to_response(
        "dashboard_app/bundle_detail.html",
        {
            'bundle_table': bundle_table,
            'bread_crumb_trail': BreadCrumbTrail.leading_to(
                bundle_detail,
                pathname=pathname,
                content_sha1=content_sha1),
            "terms_data": bundle_table.prepare_terms_data(view),
            "search_data": bundle_table.prepare_search_data(view),
            "discrete_data": bundle_table.prepare_discrete_data(view),
            "times_data": bundle_table.prepare_times_data(view),
            "site": Site.objects.get_current(),
            "bundle": bundle,
            "bundle_stream": bundle_stream,
            "next_bundle": next_bundle,
            "previous_bundle": previous_bundle,
        },
        RequestContext(request))
Пример #42
0
def timetable(request, organization, project_id):
    organization = get_object_or_404(Organization, name=organization)
    project = get_object_or_404(Project, id=project_id)

    setting, _ = Setting.objects.get_or_create(user=request.user)
    timezone = pytz.timezone(str(setting.timezone))

    if not project.is_member(request.user):
        return HttpResponseForbidden()

    tl_activate(setting.locale)
    tz_activate(timezone)

    time_records = TimeRecordTable(project.timerecord_set.all(),
                                   request=request)
    request.session['timetable.sort'] = request.GET.get(
        'sort') or request.session.get('timetable.sort')
    time_records.order_by = request.session.get(
        'timetable.sort') or '-end_time'
    RequestConfig(request, paginate={'per_page': 15}).configure(time_records)

    form_add_record = TimeRecordForm(
        initial={
            "start_time": datetime.now(timezone).strftime('%Y-%m-%dT%H:%M')
        })
    form_edit_record = TimeRecordForm(
        initial={
            "end_time": datetime.now(timezone).strftime('%Y-%m-%dT%H:%M')
        })

    context = dict(organization=organization,
                   project=project,
                   time_records=time_records,
                   form_add_record=form_add_record,
                   form_edit_record=form_edit_record)
    return render(request, 'tracker/timetable.html', context)
Пример #43
0
def detail_ontology_term(request, pk=None):
    """
    Detailed view of Ontology
    """
    variable_dict = {}
    phenotypes = []
    if pk is not None:
        term = OntologyTerm.objects.get(pk=pk)
        variable_dict["object"] = term
        db_field = _get_db_field_from_source(term.source) + '_id__in'
        ids = _get_ontology_terms(term)
        #necessary because sqlite has a limit of 999 SQL variables
        ids = [ids[i:i + 500] for i in range(0, len(ids), 500)]
        for sub in ids:
            kwargs = {db_field: sub}
            phenotypes.extend(Phenotype.objects.published().filter(**kwargs))
    variable_dict['phenotype_count'] = len(phenotypes)
    phenotype_table = PhenotypeTable(phenotypes, order_by="-name")
    RequestConfig(request, paginate={
        "per_page": 20
    }).configure(phenotype_table)
    variable_dict["phenotype_table"] = phenotype_table
    return render(request, 'phenotypedb/ontologyterm_detail.html',
                  variable_dict)
Пример #44
0
def room_list(request, room_id):
    """Displays an array of devices and add export in .xls.

    Arguments:
        room_id {int} -- room.id
    """
    get_room = get_object_or_404(Room, id=room_id)

    if get_room.residence in Residence.objects.filter(user=request.user):
        equipments = EquipmentTable(Equipment.objects.filter(room=get_room))

        RequestConfig(request).configure(equipments)

        export_format = request.GET.get('_export', None)
        if TableExport.is_valid_format(export_format):
            exporter = TableExport(export_format, equipments)
            return exporter.response('equipments.{}'.format(export_format))
    else:
        raise Http404()

    return render(request, 'myapp/room/room_list.html', {
        'room': get_room,
        'equipments': equipments,
    })
Пример #45
0
 def get_table(self, **kwargs):
     session = getattr(self.request, 'session', False)
     entity = self.kwargs.get('entity')
     selected_cols = self.request.GET.getlist("columns")
     if session:
         edit_v = self.request.session.get('edit_views', False)
     else:
         edit_v = False
     if 'table_fields' in settings.APIS_ENTITIES[entity.title()]:
         default_cols = settings.APIS_ENTITIES[
             entity.title()]['table_fields']
     else:
         default_cols = ['name']
     default_cols = default_cols + selected_cols
     self.table_class = get_entities_table(self.entity.title(),
                                           edit_v,
                                           default_cols=default_cols)
     table = super(GenericListViewNew, self).get_table()
     RequestConfig(self.request,
                   paginate={
                       'page': 1,
                       'per_page': self.paginate_by
                   }).configure(table)
     return table
Пример #46
0
def auto_billings(request):
    logger.info('function_call auto_billings(request) ->')

    billings = Billing.objects.all()

    if request.method == 'POST':
        if request.POST.get('action') == "delete":
            billing = Billing.objects.get(
                id=int(request.POST.get('id_record')))
            billing.delete()

            form = BillingForm()

        else:
            form = BillingForm(request.POST)

            if form.is_valid():
                form.save()
                form = BillingForm()
    else:
        form = BillingForm()

    table = BillingTable(billings)
    RequestConfig(request, paginate={"per_page": 20}).configure(table)

    c = {
        'table': table,
        'form': form,
        'user': request.user,
        'SITENAME': settings.SITENAME,
        'management': request.user.has_perm('auth.management')
    }
    c.update(csrf(request))
    return render_to_response('auto_billings.html',
                              c,
                              context_instance=RequestContext(request))
Пример #47
0
def image_metadata_list(request):
    """ A list of all the metadata the user has created. """
    # The user is trying to delete the selected metadata
    if request.method == "POST":
        pks = request.POST.getlist("selection")
        # Get all of the checked metadata (except LOCKED metadata)
        selected_objects = ImageMetadata.objects.filter(pk__in=pks,
                                                        locked=False)
        selected_objects.delete()
        messages.success(request, 'Metadata successfully deleted')
        return redirect('ingest:image_metadata_list')
    # This is the GET (just show the user their list of metadata)
    else:
        # XXX: This exclude is likely redundant, becaue there's already the
        # same exclude in the class itself. Need to test though.
        table = ImageMetadataTable(
            ImageMetadata.objects.filter(user=request.user),
            exclude=['user', 'bil_uuid'])
        RequestConfig(request).configure(table)
        image_metadata = ImageMetadata.objects.filter(user=request.user)
        return render(request, 'ingest/image_metadata_list.html', {
            'table': table,
            'image_metadata': image_metadata
        })
Пример #48
0
def home(request):
    print('go upload file')
    #open file location
    file = open('./readcsv/csv/outrasmsg.csv')
    data = file.read()
    print(data)

    table = MessagesTable(Messages.objects.all())
    RequestConfig(request).configure(table)
    return render(request, './table.html', {'table': table, 'dinamic': data})

# def upload(request):
#     print('go upload file')
#     #open file location
#     file = open('./readcsv/csv/outrasmsg.csv')
#     data = file.read()
#     print(data)
#     print(request.user)
#     # request.user.message_set.create(dinamic = data)
#     # file = File.open('csv/teste2-relatorios.csv')

#     table = MessagesTable(Messages.objects.all())
#     RequestConfig(request).configure(table)
#     return render(request, './table.html', {'table': table, 'dinamic': data})
Пример #49
0
    def get(self, request, pk):

        aggregate = get_object_or_404(Aggregate, pk=pk)

        # Find all child prefixes contained by this aggregate
        child_prefixes = Prefix.objects.filter(
            prefix__net_contained_or_equal=str(aggregate.prefix)
        ).select_related(
            'site', 'role'
        ).annotate_depth(
            limit=0
        )
        child_prefixes = add_available_prefixes(aggregate.prefix, child_prefixes)

        prefix_table = tables.PrefixTable(child_prefixes)
        if request.user.has_perm('ipam.change_prefix') or request.user.has_perm('ipam.delete_prefix'):
            prefix_table.base_columns['pk'].visible = True

        paginate = {
            'klass': EnhancedPaginator,
            'per_page': request.GET.get('per_page', settings.PAGINATE_COUNT)
        }
        RequestConfig(request, paginate).configure(prefix_table)

        # Compile permissions list for rendering the object table
        permissions = {
            'add': request.user.has_perm('ipam.add_prefix'),
            'change': request.user.has_perm('ipam.change_prefix'),
            'delete': request.user.has_perm('ipam.delete_prefix'),
        }

        return render(request, 'ipam/aggregate.html', {
            'aggregate': aggregate,
            'prefix_table': prefix_table,
            'permissions': permissions,
        })
Пример #50
0
 def get_context_data(self, **kwargs):
     # self.source_model.objects.filter()
     ctx = super(MappingCreatorView, self).get_context_data(**kwargs)
     form = FilterSelectForm(self.request.GET,
                             initial={"item_per_page": self.item_per_page})
     ctx["form"] = form
     # if form.is_valid():
     #     mapping = MappingRelation.objects.filter(source_content_type=form.cleaned_data["source_content"],
     #                                              target_content_type=form.cleaned_data["target_content"])
     if form.is_valid():
         t = MappingCreatorTable(self.source_model, self.target_model,
                                 self.source_model.objects.all())
         RequestConfig(self.request,
                       paginate={
                           "per_page": form.cleaned_data["item_per_page"]
                       }).configure(t)
         # t = MappingCreatorTable(NsnUpperLevelTeam.objects.all())
         ctx["table"] = t
         ctx["target_autocomplete_url"] = '/ajax_select/ajax_lookup/%s' % \
                                          get_low_case_model_class_name(self.target_model)
     else:
         ctx["table"] = None
         ctx["target_autocomplete_url"] = ''
     return ctx
Пример #51
0
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)
    )
Пример #52
0
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))
Пример #53
0
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)
Пример #54
0
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 cinema_table_all(request):
    """
    Returns all Cinema entities as a table

    :param request:
    :return: Cinema's table
    """

    config = RequestConfig(request)
    if request.user.is_staff is True:
        content = CinemaTableEditable(Cinema.objects.all())
        config.configure(content)
        return render(request, 'tables/cinema/cinema-table-editable.html', {
            'table': content,
            'cinema_id': Staff.objects.get(user_id=request.user.pk).cinema_id.id,
            "staff": Staff.objects.get(user_id=request.user.pk)
        })
    else:
        content = CinemaTableUneditable(Cinema.objects.all())
        config.configure(content)
        return render(request, 'tables/cinema/cinema-table-uneditable.html', {
            'table': content,
        })
Пример #56
0
def statementofaccnew(request):
    loggedusers = userselection(request)
    branchselectlist = branchselection(request)
    terminallist = terminalselection(request)
    menubar = navbar(request)
    branchid = request.session.get(CONST_branchid)
    loguser = User.objects.get(id=request.session.get('userid'))
    formdata = {
        'customerinput': '',
        'datefrom': '',
        'dateto': datetime.now().strftime('%Y-%m-%d'),
    }
    if branchid == '-1':
        customerlist = Customer.objects.all()
    else:
        customerlist = Customer.objects.filter(branch__id=branchid)
    if request.method == 'POST':
        if 'customerinput' in request.POST:
            customerid = request.POST['customerinput']
            date_from = request.POST['datefrom']
            date_to = request.POST['dateto']
            formdata = {
                'customerinput': customerid,
                'datefrom': date_from,
                'dateto': date_to,
            }
            date_to = datetime.strptime(date_to, '%Y-%m-%d')
            date_to = date_to + timedelta(days=1)

            if customerid == 'all' or customerid == 'outstanding':
                if branchid == '-1':
                    oldstatements = StatementOfAccount.objects.all()
                    selectedcustomers = Customer.objects.all()
                else:
                    oldstatements = StatementOfAccount.objects.filter(
                        branch__id=branchid)
                    selectedcustomers = Customer.objects.filter(
                        branch__id=branchid)
            else:
                oldstatements = StatementOfAccount.objects.filter(
                    branch__id=branchid)
                selectedcustomers = Customer.objects.filter(id=customerid)
            for statement in oldstatements:
                statement.delete()
            for selectedcustomer in selectedcustomers:
                newcustid = selectedcustomer.id
                if date_from:
                    invoicelist1 = Invoice.objects.filter(
                        customer__id=newcustid,
                        createtimestamp__gte=date_from,
                        createtimestamp__lte=date_to)
                    invoicelist2 = Invoice.objects.filter(
                        customer__id=newcustid, createtimestamp__lte=date_from)
                    invoicelist2 = invoicelist2.filter(
                        payment__lt=models.F('total'))
                    invoicelist = (invoicelist1 | invoicelist2)
                    paymentlist = Payment.objects.filter(
                        customer=selectedcustomer,
                        createtimestamp__gte=date_from,
                        createtimestamp__lte=date_to)
                else:
                    invoicelist = Invoice.objects.filter(
                        customer__id=newcustid, createtimestamp__lte=date_to)
                    invoicelist = invoicelist.filter(
                        payment__lt=models.F('total'))
                    paymentlist = None
                user = User.objects.get(id=request.session.get('userid'))
                if date_from:
                    statementofacc = StatementOfAccount(
                        customer=selectedcustomer,
                        datefrom=date_from,
                        dateto=date_to,
                        created_by=user,
                        createtimestamp=timezone.now(),
                        branch=selectedcustomer.branch)
                else:
                    statementofacc = StatementOfAccount(
                        customer=selectedcustomer,
                        dateto=date_to,
                        created_by=user,
                        createtimestamp=timezone.now(),
                        branch=selectedcustomer.branch)
                statementofacc.id = newcustid + '_' + timezone.now().strftime(
                    "%d/%m/%Y %H:%M%p")
                statementofacc.save()
                totalamt = 0.0
                paidamt = 0.0

                for inv in invoicelist:
                    totalamt = totalamt + float(inv.total)

                    try:
                        payment = float(inv.payment)
                    except:
                        payment = 0.0
                    paidamt = paidamt + max([payment, 0])
                    soainv = StatementOfAccountInvoice(soa=statementofacc)
                    soainv.id = statementofacc.id + '_' + inv.invoiceno
                    soainv.date = inv.createtimestamp.date()
                    soainv.reference = inv.invoiceno
                    soainv.description = inv.remarks
                    if date_from:
                        soainv.debit = inv.total
                    else:
                        soainv.debit = float(inv.total) - payment
                    soainv.credit = 0
                    soainv.save()
                outstandingamt = totalamt - paidamt
                statementofacc.totalamount = totalamt
                statementofacc.paidamount = paidamt
                statementofacc.outstandindamount = outstandingamt
                statementofacc.save(update_fields=[
                    "totalamount", 'paidamount', 'outstandindamount'
                ])
                if paymentlist:
                    for pmt in paymentlist:
                        soainv = StatementOfAccountInvoice(soa=statementofacc)
                        soainv.id = statementofacc.id + '_' + pmt.id
                        soainv.date = pmt.createtimestamp.date()
                        soainv.reference = pmt.id
                        soainv.description = pmt.payment_paymenttype.name
                        soainv.debit = 0
                        soainv.credit = pmt.total
                        soainv.save()

            if customerid == 'outstanding':
                nonoutstandingsoa = StatementOfAccount.objects.filter(
                    outstandindamount=0)
                for soa in nonoutstandingsoa:
                    soa.delete()
    if branchid == '-1':
        statementofacc_list = StatementOfAccount.objects.all().order_by(
            'customer__name')
    else:
        statementofacc_list = StatementOfAccount.objects.filter(
            customer__branch__id=branchid).order_by('customer__name')
    final_StatementOfAccount_table = StatementOfAccountTable(
        statementofacc_list)

    RequestConfig(request, paginate={
        'per_page': 25
    }).configure(final_StatementOfAccount_table)
    context = {
        'formdata': formdata,
        'nav_bar': sorted(menubar.items()),
        'branchselection': branchselectlist,
        'terminalselection': terminallist,
        'loggedusers': loggedusers,
        'customerlist': customerlist,
        'title': "Statement of account",
        'isedit': True,
        'issuperuser': loguser.is_superuser,
        'isall': branchid != '-1',
        'header': "Statement of account",
        'statementofacc': final_StatementOfAccount_table,
    }
    return render(request, 'statementofaccount_new.html', context)
Пример #57
0
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})
Пример #58
0
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))