def set_filters(self, request): _start = date.today().replace(day=1) _end = (_start + timedelta(days=33)).replace(day=1) - timedelta(days=1) filters = dict( data=dict(start_datetime=[ _start.strftime('%d.%m.%Y'), _end.strftime('%d.%m.%Y'), ]), ordered=['branch', 'start_datetime', 'master'], fields=dict( branch=dict(label='Филиал', key='branch__in', widget=dict(attrs={}, name='SelectMultiple', input_type='select', choices=get_choices( request, 'company.Branch'))), start_datetime=dict(label='Период', key='start_datetime', widget=dict(attrs={}, name="DateInput", input_type="daterange")), master=dict(label='Правщик', key='master', widget=dict(attrs={}, name="Select", input_type="select", choices=get_choices( request, 'company.Master'))), )) filters = self.get_filters(request, filters=filters) filters = filters_choices(request, filters, self.model) return filters
def set_filters(self, request): _start = date.today().replace(day=1) _end = (_start + timedelta(days=33)).replace(day=1) - timedelta(days=1) filters = dict( data=dict( start_datetime=[_start.strftime('%d.%m.%Y'), _end.strftime('%d.%m.%Y')], status='closed' ), ordered=['branch', 'start_datetime', 'manager', 'master', 'persons__control', 'status'], fields=dict( branch=dict( label='Филиал', key='branch__in', widget=dict( attrs={}, name='SelectMultiple', input_type='select', choices=get_choices(request, 'company.Branch') ) ), start_datetime=dict( label='Период', key='start_datetime', widget=dict( attrs={}, name="DateInput", input_type="daterange" ) ), manager=dict( label='Организатор', key='manager', widget=dict( attrs={}, name="Select", input_type="select", choices=get_choices(request, 'company.Manager') ) ), master=dict( label='Правщик', key='master', widget=dict( attrs={}, name="Select", input_type="select", choices=get_choices(request, 'company.Master') ) ), persons__control=dict( label='Тип услуги', key='rel_persons__control', widget=dict( attrs={}, name="Select", input_type="select", choices=[dict(label="Правка", value=False), dict(label="Контроль", value=True)] ) ), status=dict( label='Статус сделки', key='status', widget=dict( attrs={}, name="Select", input_type="select", choices=[dict(label="Завершенные", value='closed'), dict(label="В работе", value='in_work')] ) ), ) ) return self.get_filters(request=request, filters=filters)
def dispatch(self, request, *args, **kwargs): self.model = get_model(self.kwargs.get('model_name')) self.permissions = self.model.get_permissions(request) if 'view' not in self.permissions: return JsonResponse(dict(answer='No permissions'), safe=False) self.formset_errors = dict() self.action = kwargs.get('action', None) self.kwargs.update(kwargs) if request.method == 'GET': for key, value in self.request.GET.items(): self.kwargs[key] = value[0] if isinstance(value, list) else value self.parents = getattr(self.model, 'list_parents', []) if self.kwargs.get('related_name'): self.kwargs.update({'model': self.model}) for parent in self.parents: if self.request.GET.get(parent): self.kwargs.update({parent: self.request.GET.get(parent)}) print('PARENT', parent, self.request.GET.get(parent)) if kwargs.get('pk'): self.object = self.model.objects.get(pk=kwargs['pk']) if self.model._meta.label == 'company.Branch': if self.object.id in get_choices(self.request, 'company.Branch', True): self.permissions += ['change', 'view', 'add'] return super().dispatch(request, *args, **kwargs)
def get_items(self): items = [] request_dict = self.request.GET.dict() request_dict.pop('get', None) if len(request_dict.keys()) <= 0: return items expense_q = self.get_queryset() # Фильтр только по ответственным филиалам if not self.request.user.has_perm('Администраторы'): expense_q = expense_q.filter( branch__in=get_choices(self.request, 'company.Branch', get_list=True), created_by=self.request.user.person).exclude( type__name='Заработная плата') self.count = expense_q.count() for q_item in expense_q: item = dict() for field_name in self.list_display + ['description']: _q_item = q_item for field in field_name.split('__'): try: _q_item = getattr(q_item, 'get_%s_display' % field)() except AttributeError: _q_item = getattr(_q_item, field) item[field_name] = _q_item.__str__() if _q_item else '' self.total += q_item.value items.append(item) return items
def get_items(self): items = [] _queryset = self.get_queryset() if (self.request.GET.get('phones') and len(self.request.GET.get('phones')) > 6) or \ (self.request.GET.get('full_name') and len(self.request.GET.get('full_name')) > 3): pass else: _queryset = _queryset.filter( rel_deals__deal__branch__in=get_choices( self.request, 'company.Branch', get_list=True)) self.count = _queryset.count() self.paging['pages'] = round(self.count / self.paging['page_items'] + 0.5) begin = (self.paging['page'] - 1) * self.paging['page_items'] for q_item in _queryset[begin:begin + self.paging['page_items']]: item = {'actions': self.get_item_actions(q_item.pk)} for field_name in self.list_display: _q_item = q_item for field in field_name.split('__'): try: _q_item = getattr(q_item, 'get_%s_display' % field)() except AttributeError: if hasattr(_q_item, field): _q_item = getattr(_q_item, field) item[field_name] = _q_item.__str__() if _q_item else '' items.append(item) return items
def get(self, request, *args, **kwargs): if 'view' not in self.permissions: return JsonResponse(dict(answer='No permissions'), safe=False) items = get_choices(request, 'deal.Service') context = { 'items': items } return JsonResponse(context, safe=False)
def get_items(self): items = [] _queryset = self.get_queryset() # TODO: отфильтровать по группам доступа if self.model.__name__.lower() == 'servicetimetable': _queryset = _queryset.filter(service__in=get_choices( self.request, 'deal.Service', get_list=True)) elif self.model.__name__.lower() == 'client': if (self.request.GET.get('phones') and len(self.request.GET.get('phones')) > 5) or \ (self.request.GET.get('full_name') and len(self.request.GET.get('full_name')) > 3): pass else: _queryset = _queryset.filter( Q(rel_deals__deal__branch__in=get_choices( self.request, 'company.Branch', get_list=True)) | Q(rel_deals=None)) begin = 1 self.count = _queryset.count() if self.count: self.paging['pages'] = round(self.count / self.paging['page_items'] + 0.5) self.paging['page'] = \ self.paging['page'] if self.paging['page'] <= self.paging['pages'] else self.paging['pages'] begin = (self.paging['page'] - 1) * self.paging['page_items'] for q_item in _queryset[begin:begin + self.paging['page_items']]: item = dict() # {'actions': self.get_item_actions(q_item.pk)} for field_name in self.list_display: _q_item = q_item for field in field_name.split('__'): try: _q_item = getattr(q_item, 'get_%s_display' % field)() except AttributeError: if hasattr(_q_item, field): _q_item = getattr(_q_item, field) item[field_name] = _q_item.__str__() if _q_item else '' items.append(item) return items
def render_to_response(self, context, **response_kwargs): if 'view' not in self.permissions: return HttpResponse('no perm') formset_list, formset = self.get_formset() _form = RemoteForm(self.get_form(), model=self.model, csrf_token=csrf.get_token(self.request)).as_dict() # TODO: отфильтровать по группам доступа if self.model.__name__.lower() == 'expense': _form['fields']['branch']['widget']['choices'] = get_choices( self.request, 'company.Branch') elif self.model.__name__.lower() == 'servicetimetable': _form['fields']['service']['widget']['choices'] = get_choices( self.request, 'deal.Service') title, tabs = self.get_tabs() if self.get_form().is_valid() and not self.formset_errors: message = dict(type='success', text='Сохранено') else: message = dict(type='warning', text='Ошибка') context = dict(title=title, tabs=tabs, parents=self.parents, form=_form, formset_list=formset_list, formset=formset, formset_errors=self.formset_errors, message=message, permissions=self.permissions) if self.request.GET.get('debug'): from django.shortcuts import render_to_response return render_to_response('debug.jinja2', locals()) return JsonResponse(context)
def get_queryset(self): list_related = getattr(self.model, 'list_related', []) if self.client: queryset = self.model.objects.filter( Q(client=self.client) | Q(deal__persons=self.client)) elif self.deal: queryset = self.model.objects.filter( Q(deal=self.deal) | Q(client__rel_deals__deal=self.deal)) else: # Тут начинается альтернатива self.filters_q branch = self.filters['data'].get('branch') time_planned = self.filters['data'].get('time_planned') type = self.filters['data'].get('type') start_time = datetime.strptime(time_planned[0], '%d.%m.%Y') finish_time = datetime.strptime(time_planned[1], '%d.%m.%Y') q = Q() if time_planned: q &= Q(time_planned__gte=start_time, time_planned__lte=finish_time) if branch: q &= Q(deal__branch=branch) | Q( client__rel_deals__deal__branch=branch) q |= Q(status='in_work', time_planned__lte=finish_time, deal__branch=branch) q |= Q(status='in_work', time_planned__lte=finish_time, client__rel_deals__deal__branch=branch) else: q |= Q(status='in_work', time_planned__lte=finish_time) if type: q &= Q(type=type) queryset = self.model.objects.filter(q).order_by('time_planned') # Фильтр только по ответственным филиалам if not self.client and not self.request.user.has_perm( 'Администраторы'): branch_list = get_choices(self.request, 'company.Branch', get_list=True) print('branch_list', branch_list) queryset = queryset.filter( Q(deal__branch__in=branch_list) | Q(client__rel_deals__deal__branch__in=branch_list)) return queryset.select_related(*list_related).distinct()
def get_filters(self, request): try: filters_form = eval('%sFilterForm' % self.model.__name__) except NameError: filters_form = FilterForm _fields = self.model.get_filter_fields() _filters_class = modelform_factory(self.model, form=filters_form, fields=_fields) _form = _filters_class(request=request, instance=None) _remote_form = RemoteForm(_form, model=self.model).as_dict() # TODO: отфильтровать по группам доступа if self.model.__name__.lower() == 'timetimetable': _remote_form['fields']['branch']['widget'][ 'choices'] = get_choices(self.request, 'company.Branch') return _remote_form