def tolist(qs, add_header=True, list_display=()): model = qs.model data = [] fields = [] header = [] if type(list_display) == bool or not list_display: list_display = get_metadata(model, 'list_display', fields) if list_display: for field_name in list_display: header.append(get_fiendly_name(model, field_name)) fields.append(field_name) else: for field in get_metadata(model, 'fields'): header.append(field.verbose_name) fields.append(field.name) if add_header: data.append(header) for obj in qs: row = [] for field in fields: val = getattr2(obj, field) if callable(val): val = val() row.append(format_value(val, False)) data.append(row) return data
def pre_save(self, model_instance, add): search_text = [] for attr_name in get_metadata(model_instance, 'search_fields'): tokens = attr_name.split('__') if len(tokens) == 1: if attr_name != 'ascii': val = getattr2(model_instance, attr_name) if val: search_text.append(str(to_ascii(val).upper().strip())) return ' '.join(search_text)
def create_indexes(self, instance): for log_index in get_metadata(instance.__class__, 'logging', (), iterable=True): index_object = getattr2(instance, log_index) if index_object: index_content_type = ContentType.objects.get_for_model( index_object.__class__) LogIndex.objects.create(log=self, content_type=index_content_type, object_id=index_object.pk)
def __init__(self, request, title, qs, list_display=()): header = [] rows = [] if not list_display: list_display = get_metadata(qs.model, 'list_display') for lookup in list_display: header.append(get_fiendly_name(qs.model, lookup, as_tuple=False)) for obj in qs: row = [] for lookup in list_display: row.append(getattr2(obj, lookup)) rows.append(row) super(ModelTable, self).__init__(request, title, header, rows)
def view(request, app, cls, pk, tab=None): if not request.user.is_authenticated: return httprr(request, '/admin/login/?next={}'.format(request.get_full_path())) try: _model = apps.get_model(app, cls) except LookupError as e: return page_not_found(request, e, 'error404.html') obj = _model.objects.all(request.user).filter(pk=pk).first() obj.request = request obj._user = request.user if 'one_to_many_count' in request.GET: # TODO create a specific view for this purpose return HttpResponse(getattr2(obj, request.GET['one_to_many_count'])) if not permissions.can_view(request, obj): return HttpResponseForbidden() title = str(obj) parent = request.GET.get('parent', None) printable = get_metadata(_model, 'pdf', False) widget_panel = ModelDashboard(request, obj, tab, parent, printable=printable) widget_panel.process_request() if widget_panel.model_panel.message: return httprr(request, request.get_full_path(), widget_panel.model_panel.message) log_data = get_metadata(obj.__class__, 'log', False) if log_data and request.user.is_superuser and request.user.has_perm( 'admin.list_log'): url = '/log/{}/{}/'.format(app, cls) widget_panel.model_panel.drop_down.add_action( '{} {}'.format(_('View'), _('Log')), url, 'ajax', 'fa fa-history') return render(request, 'default.html', locals())
def _configure_list_display(self): hidden_fields = [] if not self.list_display: self.list_display = list( get_metadata(self.qs.model, 'list_display', [])) if not self.list_display: fields = [] for field in get_metadata(self.qs.model, 'fields'): if not hasattr(field, 'display') or field.display: fields.append(field) for field in get_metadata(self.qs.model, 'local_many_to_many'): if not hasattr(field, 'display') or field.display: fields.append(field) for field in fields[1:6]: if not field.name.endswith( '_ptr') and not field.name == 'ascii' and not type( field).__name__ == 'TreeIndexField': if not hasattr(field, 'display') or field.display: self.list_display.append(field.name) for field_name in self.list_display: if '__' in field_name: attr = getattr2(self.qs.model, field_name) else: attr = getattr(self.qs.model, field_name) if hasattr(attr, 'field_name'): field = getattr(self.qs.model, '_meta').get_field(attr.field_name) if hasattr(field, 'display') and not field.display: hidden_fields.append(field_name) if self.relation and (field_name == self.relation.hidden_field_name or field_name.startswith('{}__'.format( self.relation.hidden_field_name))): hidden_fields.append(field_name) if self.exclude: for field_name in self.exclude: if field_name in self.list_display: hidden_fields.append(field_name) for field_name in hidden_fields: self.list_display.remove(field_name)
def can_edit(self): if self._user: if self._user.organization_id or self._user.unit_id or not self._user.is_superuser: model = type(self) app_label = get_metadata(model, 'app_label') perm_name = '%s.edit_%s' % (app_label, model.__name__.lower()) if self._user.has_perm(perm_name): permission_mapping = self._user.get_permission_mapping( model) if 'edit_lookups' in permission_mapping and permission_mapping[ 'edit_lookups']: for lookup, values in permission_mapping[ 'edit_lookups']: value = getattr2(self, lookup) value = hasattr(value, 'pk') and value.pk or value if value in values: return True return False else: return False return True
def can_delete(self): if self._user: if not self._user.is_superuser: model = type(self) app_label = get_metadata(model, 'app_label') perm_name = '{}.delete_{}'.format(app_label, model.__name__.lower()) if self._user.has_perm(perm_name): permission_mapping = self._user.get_permission_mapping( model) if 'delete_lookups' in permission_mapping and permission_mapping[ 'delete_lookups']: for lookup, values in permission_mapping[ 'delete_lookups']: value = getattr2(self, lookup) value = hasattr(value, 'pk') and value.pk or value if value in values: return True return False else: return False return True
def get_action_form(request, obj, action): action_function = action['function'] action_verbose_name = action['verbose_name'] initial = action['initial'] action_input = action['input'] action_choices = action['choices'] action_display = action['display'] app_label = get_metadata(type(obj), 'app_label') func = getattr(obj, action_function.__name__, action_function) if initial and hasattr(obj, initial): initial = getattr(obj, initial)() else: initial = {} if action_choices and hasattr(obj, action_choices): action_choices = getattr(obj, action_choices)() else: action_choices = {} if action_input: # it is a form name if type(action_input) in [str, str] and '.' not in action_input: full_app_name = settings.APP_MAPPING.get(app_label, app_label) fromlist = app_label module = __import__('{}.forms'.format(full_app_name), fromlist=list(map(str, [app_label]))) form_cls = getattr(module, action_input) # it is a model or model name else: if type(action_input) in [str, str]: app_name, class_name = action_input.split('.') action_input = apps.get_model(app_name, class_name) class Form(forms.ModelForm): class Meta: model = action_input fields = get_parameters_names(func) title = action_verbose_name submit_label = action_verbose_name form_cls = Form else: class Form(forms.ModelForm): class Meta: model = func.__self__.__class__ fields = get_parameters_names(func) title = action_verbose_name submit_label = action_verbose_name form_cls = Form if issubclass(form_cls, forms.ModelForm): for key in list(initial.keys()): if hasattr(obj, key) and obj.pk and getattr(obj, key): del (initial[key]) form = form_cls(request, instance=obj, initial=initial) else: form = form_cls(request, initial=initial) if action_display: for lookup in action_display: label = get_fiendly_name(func.__self__.__class__, lookup) value = getattr2(obj, lookup) form.fields[lookup] = forms.CharField( label=label, initial=value, required=False, widget=forms.widgets.DisplayInput(value)) if action_choices: for field_name in action_choices: form.fields[field_name].queryset = action_choices[field_name] if not obj.pk: verbose_name = get_metadata(obj.__class__, 'verbose_name') form.fields['instance'] = forms.ModelChoiceField( type(obj).objects.all(), label=verbose_name) if form.fieldsets: form.fieldsets = ((verbose_name, { 'fields': ('instance', ) }), ) + form.fieldsets return form
def check_role(self, saving=True): role_name = get_metadata(self.__class__, 'role_name') role_username = get_metadata(self.__class__, 'role_username') verbose_name = get_metadata(self.__class__, 'verbose_name') concrete_fields = get_metadata(self.__class__, 'concrete_fields') role_email = get_metadata(self.__class__, 'role_email', '') role_scope = get_metadata(self.__class__, 'role_scope') if role_username: from django.contrib.auth.models import Group from djangoplus.admin.models import Role, Organization, OrganizationRole, Unit, UnitRole group_name = verbose_name username = getattr2(self, role_username) name = role_name and getattr2(self, role_name) or None if username: unit = Unit.objects.get(pk=0) organization = organization = Organization.objects.get(pk=0) if issubclass(self.__class__, Organization): organization = self unit = None elif issubclass(self.__class__, Unit): unit = self organization = None elif role_scope: scope = getattr2(self, role_scope) if issubclass(scope.__class__, Organization): organization = scope unit = None elif issubclass(scope.__class__, Unit): unit = scope organization = None else: for field in concrete_fields: if hasattr(field, 'rel') and hasattr(field.rel, 'to'): if issubclass(field.rel.to, Organization): organization = getattr(self, field.name) unit = None break if issubclass(field.rel.to, Unit): unit = getattr(self, field.name) organization = None break email = role_email and getattr2(self, role_email) or '' User = get_user_model() group = Group.objects.get_or_create(name=group_name)[0] if unit and not organization: for field in get_metadata(unit.__class__, 'concrete_fields'): if hasattr(field, 'rel') and hasattr(field.rel, 'to'): if issubclass(field.rel.to, Organization): organization = getattr(unit, field.name) if saving: qs = User.objects.filter(username=username) if qs.exists(): user = qs[0] user.email = email user.name = name or unicode(self) user.save() else: user = User() user.username = username user.name = name or unicode(self) user.email = email user.set_password(settings.DEFAULT_PASSWORD) user.save() user.groups.add(group) if organization: role = Role.objects.get(user=user, group=group) if not OrganizationRole.objects.filter( role=role, organization=organization).exists(): organization_role = OrganizationRole() organization_role.role = role organization_role.organization = organization organization_role.save() if unit: role = Role.objects.get(user=user, group=group) if not UnitRole.objects.filter(role=role, unit=unit).exists(): unit_role = UnitRole() unit_role.role = role unit_role.unit = unit unit_role.save() else: user = User.objects.get(username=username) if unit or organization: keep_in_group = False if organization: OrganizationRole.objects.filter( role__user=user, role__group=group, organization=organization).delete() if OrganizationRole.objects.filter( role__user=user, role__group=group).exists(): keep_in_group = True if unit: UnitRole.objects.filter(role__user=user, role__group=group, unit=unit).delete() if UnitRole.objects.filter( role__user=user, role__group=group).exists(): keep_in_group = True if not keep_in_group: user.groups.remove(group) else: UnitRole.objects.filter(role__user=user, role__group=group).delete() user.groups.remove(group)