Пример #1
0
    def init_with_context(self, context):

        admin_site_name = get_admin_site_name(context)

        self.children += [
            items.MenuItem(
                title="",
                children=[
                    items.MenuItem(
                        capfirst(_("dashboard")),
                        icon="icon-home",
                        url=reverse("%s:index" % admin_site_name),
                        description=capfirst(_("dashboard")),
                    )
                ],
            ),
            items.ModelList(
                capfirst(_("catalogue")),
                models=(
                    "authors.models.Author",
                    "books.models.BookCategory",
                    "cds.models.CdCategory",
                    "dvds.models.DvdCategory",
                ),
            ),
        ]
Пример #2
0
    def format_callback(obj):
        has_admin = obj.__class__ in admin_site._registry
        opts = obj._meta

        no_edit_link = '%s: %s' % (capfirst(opts.verbose_name),
                                   force_text(obj))

        if has_admin:
            try:
                admin_url = reverse('%s:%s_%s_change'
                                    % (admin_site.name,
                                       opts.app_label,
                                       opts.model_name),
                                    None, (quote(obj._get_pk_val()),))
            except NoReverseMatch:
                # Change url doesn't exist -- don't display link to edit
                return no_edit_link

            p = '%s.%s' % (opts.app_label,
                           get_permission_codename('delete', opts))
            if not user.has_perm(p):
                perms_needed.add(opts.verbose_name)
            # Display a link to the admin page.
            return format_html('{}: <a href="{}">{}</a>',
                               capfirst(opts.verbose_name),
                               admin_url,
                               obj)
        else:
            # Don't display link to edit, because it either has no
            # admin or is edited inline.
            return no_edit_link
Пример #3
0
 def date_error_message(self, lookup_type, field, unique_for):
     opts = self._meta
     return _(u"%(field_name)s must be unique for %(date_field)s %(lookup)s.") % {
         'field_name': unicode(capfirst(opts.get_field(field).verbose_name)),
         'date_field': unicode(capfirst(opts.get_field(unique_for).verbose_name)),
         'lookup': lookup_type,
     }
Пример #4
0
    def init_with_context(self, context):

        admin_site_name = get_admin_site_name(context)

        if "django.contrib.sites" in settings.INSTALLED_APPS:
            from django.contrib.sites.models import Site

            site_name = Site.objects.get_current().name
            site_url = "http://" + Site.objects.get_current().domain
        else:
            site_name = capfirst(_("site"))
            site_url = "/"

        self.children += [
            items.MenuItem(site_name, url=site_url, css_classes=["branding", "no-border"]),
            items.MenuItem(
                capfirst(_("dashboard")),
                icon="icon-home",
                url=reverse("%s:index" % admin_site_name),
                description=capfirst(_("dashboard")),
            ),
            items.AppList(
                capfirst(_("applications")),
                icon="icon-tasks",
                exclude=("django.contrib.*",),
                check_if_user_allowed=lambda user: user.is_staff,
            ),
            items.AppList(
                capfirst(_("administration")),
                icon="icon-cogs",
                models=("django.contrib.*",),
                check_if_user_allowed=lambda user: user.is_staff,
            ),
            items.UserTools(url=None, css_classes=["float-right"], check_if_user_allowed=lambda user: user.is_staff),
        ]
Пример #5
0
 def get_ordering_field(self):
     if self._meta.order_by:
         if isinstance(self._meta.order_by, (list, tuple)):
             choices = [(f, capfirst(f)) for f in self._meta.order_by]
         else:
             choices = [(f, capfirst(f)) for f in self.filters]
         return forms.ChoiceField(label="Ordering", required=False, choices=choices)
Пример #6
0
 def save(self, old_record, list_record, detail_record):
     if old_record is not None:
         return
     if list_record['location'] == '&nbsp;':
         return
     bulletin_type_lookup = self.get_or_create_lookup('bulletin_type', capfirst(list_record['bulletin_type'].lower()), list_record['bulletin_type'].upper(), make_text_slug=False)
     zone_lookups = []
     for z in detail_record['zone']:
         zone_lookup = self.get_or_create_lookup('zone', capfirst(z.lower()), z, make_text_slug=False)
         zone_lookups.append(zone_lookup)
     attributes = {
         'project_number': list_record['project_number'],
         'description': detail_record.get('description', None),
         'bulletin_type': bulletin_type_lookup.id,
         'application_date': detail_record['application_date'],
         'complete_date': detail_record['complete_date'],
         'zone': ','.join([str(z.id) for z in zone_lookups]),
         'bid': list_record['bid'],
         'nid': list_record['nid'],
     }
     self.create_newsitem(
         attributes,
         title=bulletin_type_lookup.name,
         url='http://web1.seattle.gov/dpd/luib/Notice.aspx?BID=%s&NID=%s' % (list_record['bid'], list_record['nid']),
         item_date=list_record['bulletin_date'],
         location_name=smart_title(list_record['location'])
     )
Пример #7
0
    def generic_lookup(self, request):
        if request.method != 'GET':
            return HttpResponseNotAllowed(['GET'])
        
        if 'content_type' in request.GET and 'object_id' in request.GET:
            content_type_id = request.GET['content_type']
            object_id = request.GET['object_id']
            
            obj_dict = {
                'content_type_id': content_type_id,
                'object_id': object_id,
            }

            content_type = ContentType.objects.get(pk=content_type_id)
            obj_dict["content_type_text"] = capfirst(force_text(content_type))

            try:
                obj = content_type.get_object_for_this_type(pk=object_id)
                obj_dict["object_text"] = capfirst(force_text(obj))
            except ObjectDoesNotExist:
                raise Http404
            
            resp = json.dumps(obj_dict, ensure_ascii=False)
        else:
            resp = ''
        return HttpResponse(resp, mimetype='application/json')
Пример #8
0
 def date_error_message(self, lookup_type, field, unique_for):
     opts = self._meta
     return _("%(field_name)s must be unique for %(date_field)s %(lookup)s.") % {
         "field_name": six.text_type(capfirst(opts.get_field(field).verbose_name)),
         "date_field": six.text_type(capfirst(opts.get_field(unique_for).verbose_name)),
         "lookup": lookup_type,
     }
Пример #9
0
    def format_callback(obj):
        has_admin = obj.__class__ in admin_site._registry
        opts = obj._meta

        if has_admin:
            admin_url = reverse('%s:%s_%s_change'
                                % (admin_site.name,
                                   opts.app_label,
                                   opts.object_name.lower()),
                                None, (quote(obj._get_pk_val()),))
            p = '%s.%s' % (opts.app_label,
                           opts.get_delete_permission())
            if not user.has_perm(p):
                perms_needed.add(opts.verbose_name)
            # Display a link to the admin page.
            return mark_safe(u'<span class="label label-info">%s:</span> <a href="%s">%s</a>' %
                             (escape(capfirst(opts.verbose_name)),
                              admin_url,
                              escape(obj)))
        else:
            # Don't display link to edit, because it either has no
            # admin or is edited inline.
            return mark_safe(u'<span class="label label-info">%s:</span> %s' %
                             (escape(capfirst(opts.verbose_name)),
                              escape(obj)))
Пример #10
0
    def app_mond_index(self, request, extra_context=None):
        #user = request.user
        app_label = 'Module'
        user = get_user(request)
        print >> sys.stdout,request.path
        has_module_perms = user.has_module_perms(app_label)
        app_dict = {}
        #self._registry = admin.site._registry
        for model, model_admin in self._registry.items():
            if app_label == model._meta.app_label:
                if has_module_perms:
                    perms = model_admin.get_model_perms(request)

                    # Check whether user has any perm for this module.
                    # If so, add the module to the model_list.
                    if True in perms.values():
                        info = (app_label, model._meta.module_name)
                        model_dict = {
                            'name': capfirst(model._meta.verbose_name_plural),
                            'perms': perms,
                        }
                        if perms.get('change', False):
                            try:
                                model_dict['admin_url'] = reverse('customer_admin:%s_%s_changelist' % info, current_app=self.name)
                            except NoReverseMatch:
                                pass
                        if perms.get('add', False):
                            try:
                                model_dict['add_url'] = reverse('customer_admin:%s_%s_add' % info, current_app=self.name)
                            except NoReverseMatch:
                                pass
                        if app_dict:
                            app_dict['models'].append(model_dict),
                        else:
                            # First time around, now that we know there's
                            # something to display, add in the necessary meta
                            # information.
                            app_dict = {
                                'name': app_label.title(),
                                'app_url': '',
                                'has_module_perms': True,
                                'models': [model_dict],
                            }
        if not app_dict:
            raise Http404('The requested admin page does not exist.')
        # Sort the models alphabetically within each app.
        app_dict['models'].sort(key=lambda x: x['name'])
        context = {
            'title': _('%s administration') % capfirst(app_label),
            'app_list': [app_dict],
        }
        extra_context = dict()
        extra_context['profile'] = get_user(request).get_profile();
        
        context.update(extra_context or {})

        return TemplateResponse(request, self.app_index_template or [
            'customer_login/change_form.html' ,
            #'customer_login/app_index.html'
        ], context, current_app=self.name)
Пример #11
0
 def values(self):
     """
     Returns a list of values for this field for this instance. It's a list
     so we can accomodate many-to-many fields.
     """
     # This import is deliberately inside the function because it causes
     # some settings to be imported, and we don't want to do that at the
     # module level.
     if self.field.rel:
         if isinstance(self.field.rel, models.ManyToOneRel):
             objs = getattr(self.instance.instance, self.field.name)
         elif isinstance(self.field.rel, models.ManyToManyRel): # ManyToManyRel
             return list(getattr(self.instance.instance, self.field.name).all())
     elif self.field.choices:
         objs = dict(self.field.choices).get(self.raw_value, EMPTY_VALUE)
     elif isinstance(self.field, models.DateField) or isinstance(self.field, models.TimeField):
         if self.raw_value:
             date_format, datetime_format, time_format = get_date_formats()
             if isinstance(self.field, models.DateTimeField):
                 objs = capfirst(dateformat.format(self.raw_value, datetime_format))
             elif isinstance(self.field, models.TimeField):
                 objs = capfirst(dateformat.time_format(self.raw_value, time_format))
             else:
                 objs = capfirst(dateformat.format(self.raw_value, date_format))
         else:
             objs = EMPTY_VALUE
     elif isinstance(self.field, models.BooleanField) or isinstance(self.field, models.NullBooleanField):
         objs = {True: 'Yes', False: 'No', None: 'Unknown'}[self.raw_value]
     else:
         objs = self.raw_value
     return [objs]
Пример #12
0
    def delete(self, request, *args, **kwargs):
        try:
            d = self.get_object()
            deps, msg = get_dep_objects(d)
            print(deps)
            if deps:
                messages.warning(self.request,  ('No se puede Eliminar %(name)s') % {
                    "name": capfirst(force_text(self.model._meta.verbose_name))
                    + ' "' + force_text(d) + '"'
                })
                raise Exception(msg)


            d.delete()
            msg = _(' %(name)s "%(obj)s" fuel eliminado satisfactorialmente.') % {
                'name': capfirst(force_text(self.model._meta.verbose_name)),
                'obj': force_text(d)
            }
            if not d.id:
                messages.success(self.request, msg)
                log.warning(msg, extra=log_params(self.request))
        except Exception as e:
            messages.error(request, e)
            log.warning(force_text(e), extra=log_params(self.request))
        return HttpResponseRedirect(self.success_url)
Пример #13
0
    def format_callback(obj):
        model = obj.__class__
        has_admin = model in admin_site._registry
        opts = obj._meta

        no_edit_link = '%s: %s' % (capfirst(opts.verbose_name), obj)

        if has_admin:
            if not admin_site._registry[model].has_delete_permission(request, obj):
                perms_needed.add(opts.verbose_name)
            try:
                admin_url = reverse('%s:%s_%s_change'
                                    % (admin_site.name,
                                       opts.app_label,
                                       opts.model_name),
                                    None, (quote(obj.pk),))
            except NoReverseMatch:
                # Change url doesn't exist -- don't display link to edit
                return no_edit_link

            # Display a link to the admin page.
            return format_html('{}: <a href="{}">{}</a>',
                               capfirst(opts.verbose_name),
                               admin_url,
                               obj)
        else:
            # Don't display link to edit, because it either has no
            # admin or is edited inline.
            return no_edit_link
Пример #14
0
    def init_with_context(self, context):
        """
        Please refer to the :meth:`~admin_tools.menu.items.MenuItem.init_with_context`
        documentation from :class:`~admin_tools.menu.items.MenuItem` class.
        """
        items = self._visible_models(context['request'])
        apps = {}
        for model, perms in items:
            if not perms['change']:
                continue
            app_label = model._meta.app_label
            if app_label not in apps:
                apps[app_label] = {
                    'title': capfirst(app_label.title()),
                    'url': self._get_admin_app_list_url(model, context),
                    'models': []
                }
            apps[app_label]['models'].append({
                'title': capfirst(model._meta.verbose_name_plural),
                'url': self._get_admin_change_url(model, context)
            })

        for app in sorted(apps.keys()):
            app_dict = apps[app]
            item = MenuItem(title=app_dict['title'], url=app_dict['url'])
            # sort model list alphabetically
            apps[app]['models'].sort(key=lambda x: x['title'])
            for model_dict in apps[app]['models']:
                item.children.append(MenuItem(**model_dict))
            self.children.append(item)
Пример #15
0
    def init_with_context(self, context):
        items = self._visible_models(context['request'])
        apps = {}
        for model, perms in items:
            app_label = model._meta.app_label
            if app_label not in apps:
                apps[app_label] = {
                    'title': capfirst(_(app_label.title())),
                    'url': reverse('%s:app_list' % get_admin_site_name(context), args=(app_label,)),
                    'models': []
                }
            model_dict = {}
            model_dict['title'] = capfirst(model._meta.verbose_name_plural)
            if perms['change']:
                model_dict['change_url'] = self._get_admin_change_url(model, context)
            if perms['add']:
                model_dict['add_url'] = self._get_admin_add_url(model, context)
            apps[app_label]['models'].append(model_dict)

        apps_sorted = apps.keys()
        apps_sorted.sort()
        for app in apps_sorted:
            # sort model list alphabetically
            apps[app]['models'].sort(lambda x, y: cmp(x['title'], y['title']))
            self.children.append(apps[app])
Пример #16
0
 def delete(self, request, *args, **kwargs):
     try:
         d = self.get_object()
         # rastrear dependencias OK
         deps, msg = get_dep_objects(d)
         if deps:
             messages.warning(self.request,  _('Cannot delete %(name)s') % {
                 "name": capfirst(force_text(self.model._meta.verbose_name))
                 + ' "' + force_text(d) + '"'
             })
             raise Exception(msg)
         '''
         if d.module_set.count() > 0:
             raise Exception(
                 (u"Solucion <b>%(name)s</b> tiene modulos asignados.") % {"name": d.name})
         if d.association_set.count() > 0:
             raise Exception(
                 (u"Solucion <b>%(name)s</b> está asignado en asociaciones.") % {"name": d.name})
         if d.enterprise_set.count() > 0:
             raise Exception(
                 (u"Solucion <b>%(name)s</b> está asignado en empresas.") % {"name": d.name})
         '''
         d.delete()
         msg = _('The %(name)s "%(obj)s" was deleted successfully.') % {
             'name': capfirst(force_text(self.model._meta.verbose_name)),
             'obj': force_text(d)
         }
         if not d.id:
             messages.success(self.request, msg)
             log.warning(msg, extra=log_params(self.request))
     except Exception, e:
         messages.error(request, e)
         log.warning(force_text(e), extra=log_params(self.request))
Пример #17
0
    def init_with_context(self, context):
        """
        Please refer to the :meth:`~client_admin.menu.items.MenuItem.init_with_context`
        documentation from :class:`~client_admin.menu.items.MenuItem` class.
        """
        items = self._visible_models(context['request'])
        apps = {}
        for model, perms in items:
            if not perms['change']:
                continue
            app_label = getattr(admin.site._registry[model], 'app_label', None) or model._meta.app_label
            if app_label not in apps:
                apps[app_label] = {
                    'title': capfirst(app_label.title()),
                    'url': get_admin_app_list_url(model),
                    'models': []
                }
            apps[app_label]['models'].append({
                'title': capfirst(model._meta.verbose_name_plural),
                'url': get_admin_change_url(model)
            })

        apps_sorted = apps.keys()
        apps_sorted.sort()
        for app in apps_sorted:
            app_dict = apps[app]
            item = MenuItem(title=app_dict['title'], url=app_dict['url'])
            # sort model list alphabetically
            apps[app]['models'].sort(lambda x, y: cmp(x['title'], y['title']))
            for model_dict in apps[app]['models']:
                item.children.append(MenuItem(**model_dict))
            self.children.append(item)
Пример #18
0
  def history_view(self, request, object_id, extra_context=None):
    "The 'history' admin view for this model."
    # First check if the object exists and the user can see its history.
    model = self.model
    obj = get_object_or_404(model.objects.using(request.database), pk=unquote(object_id))
    if not self.has_change_permission(request, obj):
        raise PermissionDenied

    # Then get the history for this object.
    opts = model._meta
    app_label = opts.app_label
    action_list = LogEntry.objects.using(request.database).filter(
      object_id=unquote(object_id),
      content_type__id__exact=ContentType.objects.get_for_model(model).id
    ).select_related().order_by('action_time')
    context = {
      'title': capfirst(force_text(opts.verbose_name) + " " + unquote(object_id)),
      'action_list': action_list,
      'module_name': capfirst(force_text(opts.verbose_name_plural)),
      'object': obj,
      'app_label': app_label,
      'opts': opts,
      'active_tab': 'history',
      'object_id': object_id,
      'model': ContentType.objects.get_for_model(model).model,
    }
    context.update(extra_context or {})
    return TemplateResponse(request, self.object_history_template or [
      "admin/%s/%s/object_history.html" % (app_label, opts.model_name),
      "admin/%s/object_history.html" % app_label,
      "admin/object_history.html"
      ], context, current_app=self.admin_site.name)
Пример #19
0
    def delete(self, request, *args, **kwargs):
        sid = transaction.savepoint()
        try:
            association = Association.objects.get(
                id=UserToken.get_association_id(request.session))
            if Enterprise.objects.filter(headquar__association_id=UserToken.get_association_id(request.session)).count() == 1:
                raise Exception(
                    (u"Asociación <b>%(name)s</b> no puede quedar sin ninguna sede asociada.") % {"name": association.name})

            d = self.get_object()
            # rastrear dependencias
            deps, msg = get_dep_objects(d)
            if deps:
                messages.warning(self.request,  _('Cannot delete %(name)s') % {
                    "name": capfirst(force_text(self.model._meta.verbose_name))
                    + ' "' + force_text(d) + '"'
                })
                raise Exception(msg)

            d.delete()
            msg = _('The %(name)s "%(obj)s" was deleted successfully.') % {
                'name': capfirst(force_text(self.model._meta.verbose_name)),
                'obj': force_text(d)
            }
            if not d.id:
                messages.success(self.request, msg)
                log.warning(msg, extra=log_params(self.request))
        except Exception, e:
            try:
                transaction.savepoint_rollback(sid)
            except:
                pass
            messages.error(request, e)
            log.warning(force_text(e), extra=log_params(self.request))
Пример #20
0
def _format_callback(obj, user, admin_site, levels_to_root, perms_needed):
    has_admin = obj.__class__ in admin_site._registry
    opts = obj._meta
    try:
        admin_url = reverse('%s:%s_%s_change'
                            % (admin_site.name,
                               opts.app_label,
                               opts.object_name.lower()),
                            None, (quote(obj._get_pk_val()),))
    except NoReverseMatch:
        admin_url = '%s%s/%s/%s/' % ('../'*levels_to_root,
                                     opts.app_label,
                                     opts.object_name.lower(),
                                     quote(obj._get_pk_val()))
    if has_admin:
        p = '%s.%s' % (opts.app_label,
                       opts.get_delete_permission())
        if not user.has_perm(p):
            perms_needed.add(opts.verbose_name)
        # Display a link to the admin page.
        return mark_safe(u'%s: <a href="%s">%s</a>' %
                         (escape(capfirst(opts.verbose_name)),
                          admin_url,
                          escape(obj)))
    else:
        # Don't display link to edit, because it either has no
        # admin or is edited inline.
        return u'%s: %s' % (capfirst(opts.verbose_name),
                            force_unicode(obj))
Пример #21
0
    def init_with_context(self, context):
        if self._initialized:
            return
        items = self._visible_models(context['request'])
        apps = {}
        for model, perms in items:
            app_label = model._meta.app_label
            if app_label not in apps:
                apps[app_label] = {
                    'name': django_apps.get_app_config(app_label).verbose_name,
                    'title': capfirst(app_label.title()),
                    'url': self._get_admin_app_list_url(model, context),
                    'models': []
                }
            model_dict = {}
            model_dict['title'] = capfirst(model._meta.verbose_name_plural)
            if perms['change']:
                model_dict['admin_url'] = self._get_admin_change_url(model, context)
            if perms['add']:
                model_dict['add_url'] = self._get_admin_add_url(model, context)
            apps[app_label]['models'].append(model_dict)

        apps_sorted = list(apps.keys())
        apps_sorted.sort()
        for app in apps_sorted:
            # sort model list alphabetically
            apps[app]['models'].sort(key=lambda i: i['title'])
            self.children.append(apps[app])
        self._initialized = True
Пример #22
0
    def __init__(self, data=None, **kwargs):
        # The list of parents objects  , for exemple if we are going to  create village
        # data is set to the list of parents  that is list of departemenents
        parent_item = parent_objs = None
        # The list of parent objects ,for exemple if we are creating village
        # `parents` is a list of parent village , ie list of rurale communities
        if "parents" in kwargs:
            parent_item, parent_objs = kwargs.pop("parents")
            # The list of parent of the parent's villages
            # For exemple if we are creating a village  , this  content dict  of list
            # of parent of rural communities
            # {'departements' : ""} , {"regions"}
        kwargs_ = kwargs.copy()
        kwargs = {}
        if data:
            super(AreaForm, self).__init__(data, **kwargs)
        else:
            super(AreaForm, self).__init__(**kwargs)

            # A dict of list of regions , deparetements arrondissement , commune arrondissement ,commune
            # in case we are creating  village
        if len(kwargs_) and "parents_rest" in kwargs_ and kwargs_.get("parents_rest"):
            # Get parents_rest list of objects
            kwargs_ = kwargs_.get("parents_rest")
            for attr_name, values in kwargs_:
                self.fields[attr_name] = forms.ChoiceField(
                    label=capfirst(attr_name),
                    required=False,
                    widget=forms.Select(attrs={"onchange": "this.form.submit();"}),
                    choices=as_tuple(values),
                )
                # del kwargs_[attr_name]
                # A rural communities list for exemple in case we are creating village
        if parent_item and parent_objs:
            self.fields[parent_item] = forms.ChoiceField(label=capfirst(parent_item), choices=as_tuple(parent_objs))
Пример #23
0
    def init_with_context(self, context):

        items = self._visible_models(context)
        apps = {}
        for model, perms in items:
            if not perms['change']:
                continue
            app_label = model._meta.app_label
            if app_label not in apps:
                apps[app_label] = {
                    'title': capfirst(_(app_label.title())),
                    'url': self._get_admin_app_list_url(model, context),
                    'models': []
                }
            apps[app_label]['models'].append({
                'title': capfirst(model._meta.verbose_name_plural),
                'url': self._get_admin_change_url(model, context),
                'add_url': self._get_admin_add_url(model, context),
                'description': _(u"Change"),
            })

        apps_sorted = apps.keys()
        apps_sorted.sort()
        for app in apps_sorted:
            app_dict = apps[app]
            item = MenuItem(title=app_dict['title'], url=app_dict['url'],
                            description=app_dict['title'])
            # sort model list alphabetically
            apps[app]['models'].sort(lambda x, y: cmp(x['title'], y['title']))
            for model_dict in apps[app]['models']:
                model_item = MenuItem(**model_dict)
                model_item.add_url = model_dict['add_url']
                item.children.append(model_item)
            self.children.append(item)
Пример #24
0
def display_for_field(value, field):
    from django.contrib.admin.templatetags.admin_list import _boolean_icon
    from django.contrib.admin.views.main import EMPTY_CHANGELIST_VALUE

    if field.flatchoices:
        return dict(field.flatchoices).get(value, EMPTY_CHANGELIST_VALUE)
    # NullBooleanField needs special-case null-handling, so it comes
    # before the general null test.
    elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField):
        return _boolean_icon(value)
    elif value is None:
        return EMPTY_CHANGELIST_VALUE
    elif isinstance(field, models.DateField) or isinstance(field, models.TimeField):
        if value:
            date_format = formats.get_format('DATE_FORMAT')
            datetime_format = formats.get_format('DATETIME_FORMAT')
            time_format = formats.get_format('TIME_FORMAT')
            if isinstance(field, models.DateTimeField):
                return capfirst(dateformat.format(value, datetime_format))
            elif isinstance(field, models.TimeField):
                return capfirst(dateformat.time_format(value, time_format))
            else:
                return capfirst(dateformat.format(value, date_format))
        else:
            return EMPTY_CHANGELIST_VALUE

    elif isinstance(field, models.DecimalField):
        if value is not None:
            return ('%%.%sf' % field.decimal_places) % value
        else:
            return EMPTY_CHANGELIST_VALUE
    elif isinstance(field, models.FloatField):
        return escape(value)
    else:
        return smart_str(value)
Пример #25
0
 def _set_options(self):
     self.exp = get_object_or_404(Experiment, pk=int(self.kwargs.get('exp_pk', '')))
     track_base = self.kwargs['track']
     track_data = self.kwargs.get('data', '')
     if track_base in ['cds', 'tss']:
         # This needs to be case-sensitive to get the form class later
         track_base = track_base.upper()
     if track_base in ['promoter', 'splicing', 'relcds']:
         track_model = '{base}diffdata'.format(base=track_base)
         if track_base in ['promoter', 'relcds',]:
             track_form_class = 'GeneExpDiffDataFilterForm'
         else:
             track_form_class = 'TSSExpDiffDataFilterForm'
     elif track_data in ['data', 'count']:
         track_model = '{base}{data}'.format(base=track_base,data=track_data)
         track_form_class = '{base}{data}FilterForm'.format(
             base=capfirst(track_base),
             data=capfirst(track_data))
     elif track_data == 'replicate':
         track_model = '{base}replicatedata'.format(base=track_base)
         track_form_class = '{base}ReplicateDataFilterForm'.format(
             base=capfirst(track_base))
     elif track_data == 'diff':
         track_model = '{base}expdiffdata'.format(base=track_base)
         track_form_class = '{base}ExpDiffDataFilterForm'.format(
             base=capfirst(track_base))
     else:
         track_model = track_base
         track_form_class = '{base}FilterForm'.format(base=capfirst(track_base))
     try:
         from cuff import forms as cf
         self.form_class = getattr(cf, track_form_class)
     except AttributeError:
         self.form_class = None
     self.model = get_model('cuff', track_model)
Пример #26
0
 def format(obj, account=False):
     has_admin = obj.__class__ in admin_site._registry
     opts = obj._meta
     no_edit_link = '%s: %s' % (capfirst(opts.verbose_name), force_text(obj))
     
     if has_admin:
         try:
             admin_url = reverse(
                 'admin:%s_%s_change' % (opts.app_label, opts.model_name),
                 None, (quote(obj._get_pk_val()),)
             )
         except NoReverseMatch:
             # Change url doesn't exist -- don't display link to edit
             return no_edit_link
         
         # Display a link to the admin page.
         context = (capfirst(opts.verbose_name), admin_url, obj)
         if account:
             context += (_("services to delete:"),)
             return format_html('{} <a href="{}">{}</a> {}', *context)
         return format_html('{}: <a href="{}">{}</a>', *context)
     else:
         # Don't display link to edit, because it either has no
         # admin or is edited inline.
         return no_edit_link
Пример #27
0
 def get_ordering_field(self):
     if self._meta.order_by:
         if isinstance(self._meta.order_by, (list, tuple)):
             if isinstance(self._meta.order_by[0], (list, tuple)):
                 # e.g. (('field', 'Display name'), ...)
                 choices = [(f[0], f[1]) for f in self._meta.order_by]
             else:
                 choices = []
                 for f in self._meta.order_by:
                     if f[0] == '-':
                         label = _('%s (descending)' % capfirst(f[1:]))
                     else:
                         label = capfirst(f)
                     choices.append((f, label))
         else:
             # add asc and desc field names
             # use the filter's label if provided
             choices = []
             for f, fltr in self.filters.items():
                 choices.extend([
                     (f, fltr.label or capfirst(f)),
                     ("-%s" % (f), _('%s (descending)' % (fltr.label or capfirst(f))))
                 ])
         return forms.ChoiceField(label=_("Ordering"), required=False,
                                  choices=choices)
Пример #28
0
    def init_with_context(self, context):
        if self._initialized:
            return
        items = self._visible_models(context["request"])
        apps = {}
        for model, perms in items:
            app_label = model._meta.app_label
            if app_label not in apps:
                apps[app_label] = {
                    "title": capfirst(app_label.title()),
                    "url": self._get_admin_app_list_url(model, context),
                    "models": [],
                }
            model_dict = {}
            model_dict["title"] = capfirst(model._meta.verbose_name_plural)
            if perms["change"]:
                model_dict["change_url"] = self._get_admin_change_url(model, context)
            if perms["add"]:
                model_dict["add_url"] = self._get_admin_add_url(model, context)
            apps[app_label]["models"].append(model_dict)

        apps_sorted = apps.keys()
        apps_sorted.sort()
        for app in apps_sorted:
            # sort model list alphabetically
            apps[app]["models"].sort(lambda x, y: cmp(x["title"], y["title"]))
            self.children.append(apps[app])
        self._initialized = True
Пример #29
0
    def init_with_context(self, context):
            if self._initialized:
                return
            items = self._visible_models(context['request'])
            apps = {}
            for model, perms in items:
                app_label = model._meta.app_label
                app_name = model._meta.app_label
                try:
                    app_name = model._meta.admin_app_label
                except :
                    pass
                if app_label not in apps:
                    apps[app_label] = {
                        'title': capfirst(app_name.title()),
                        'url': self._get_admin_app_list_url(model, context),
                        'models': []
                    }
                model_dict = {}
                model_dict['title'] = capfirst(model._meta.verbose_name_plural)
                if perms['change']:
                    model_dict['change_url'] = self._get_admin_change_url(model, context)
                if perms['add']:
                    model_dict['add_url'] = self._get_admin_add_url(model, context)
                apps[app_label]['models'].append(model_dict)

            apps_sorted = apps.keys()
            apps_sorted.sort()
            for app in apps_sorted:
                # sort model list alphabetically
                apps[app]['models'].sort(lambda x, y: cmp(x['title'], y['title']))
                self.children.append(apps[app])
            self._initialized = True
Пример #30
0
def packing_slip_pdf(pdf, order):
    pdf.init_letter(page_fn=create_stationery_fn(get_callable(plata.settings.PLATA_REPORTING_STATIONERY)()))

    if plata.settings.PLATA_REPORTING_ADDRESSLINE:
        pdf.address_head(plata.settings.PLATA_REPORTING_ADDRESSLINE)

    pdf.address(order.addresses()["shipping"])
    pdf.next_frame()

    pdf.p(
        u"%s: %s"
        % (
            capfirst(_("order date")),
            order.confirmed and order.confirmed.strftime("%d.%m.%Y") or _("Not confirmed yet"),
        )
    )
    pdf.spacer(3 * mm)

    pdf.h1(_("Order %09d") % order.id)
    pdf.hr()

    pdf.table(
        [(_("SKU"), capfirst(_("product")), capfirst(_("quantity")))]
        + [(item.variation.sku, unicode(item.variation), item.quantity) for item in order.items.all()],
        (2 * cm, 13.4 * cm, 1 * cm),
        pdf.style.tableHead + (("ALIGN", (1, 0), (1, -1), "LEFT"),),
    )

    if order.notes:
        pdf.spacer(10 * mm)
        pdf.p(capfirst(_("notes")), style=pdf.style.bold)
        pdf.spacer(1 * mm)
        pdf.p(order.notes)

    pdf.generate()
Пример #31
0
    def get_nav_menu(self):
        site_menu = list(self.get_site_menu() or [])
        had_urls = []

        def get_url(menu, had_urls):
            if 'url' in menu:
                had_urls.append(menu['url'])
            if 'menus' in menu:
                for m in menu['menus']:
                    get_url(m, had_urls)

        get_url({'menus': site_menu}, had_urls)

        nav_menu = SortedDict()

        for model, model_admin in self.admin_site._registry.items():
            if getattr(model_admin, 'hidden_menu', False):
                continue
            app_label = model._meta.app_label
            app_icon = None
            model_dict = {
                'title': unicode(capfirst(model._meta.verbose_name_plural)),
                'url': self.get_model_url(model, "changelist"),
                'icon': self.get_model_icon(model),
                'perm': self.get_model_perm(model, 'view'),
                'order': model_admin.order,
            }
            if model_dict['url'] in had_urls:
                continue

            app_key = "app:%s" % app_label
            if app_key in nav_menu:
                nav_menu[app_key]['menus'].append(model_dict)
            else:
                # Find app title
                app_title = unicode(app_label.title())
                if app_label.lower() in self.apps_label_title:
                    app_title = self.apps_label_title[app_label.lower()]
                else:
                    mods = model.__module__.split('.')
                    if len(mods) > 1:
                        mod = '.'.join(mods[0:-1])
                        if mod in sys.modules:
                            mod = sys.modules[mod]
                            if 'verbose_name' in dir(mod):
                                app_title = getattr(mod, 'verbose_name')
                            elif 'app_title' in dir(mod):
                                app_title = getattr(mod, 'app_title')
                #find app icon
                if app_label.lower() in self.apps_icons:
                    app_icon = self.apps_icons[app_label.lower()]

                nav_menu[app_key] = {
                    'title': app_title,
                    'menus': [model_dict],
                }

            app_menu = nav_menu[app_key]
            if app_icon:
                app_menu['first_icon'] = app_icon
            elif ('first_icon' not in app_menu or app_menu['first_icon']
                  == self.default_model_icon) and model_dict.get('icon'):
                app_menu['first_icon'] = model_dict['icon']

            if 'first_url' not in app_menu and model_dict.get('url'):
                app_menu['first_url'] = model_dict['url']

        for menu in nav_menu.values():
            menu['menus'].sort(key=sortkeypicker(['order', 'title']))

        nav_menu = nav_menu.values()
        nav_menu.sort(key=lambda x: x['title'])

        site_menu.extend(nav_menu)

        return site_menu
Пример #32
0
def get_admin_menu(context):
    request = context['request']
    apps = get_app_list(context, True)

    menu = OrderedDict()

    for app in apps:
        if not app['has_module_perms']:
            continue

        for model in app['models']:
            if not (model['perms'].get('view', False)
                    or model['perms']['change']):
                continue

            model_admin = model['model_admin']
            title = capfirst(getattr(model_admin, 'menu_group', app['name']))
            if title not in menu:
                menu[title] = make_menu_group(title)

            group = menu[title]
            submenu = make_menu_item(url=model['admin_url'],
                                     title=capfirst(
                                         getattr(model_admin, 'menu_title',
                                                 model['name'])),
                                     weight=getattr(model_admin, 'menu_order',
                                                    10))
            group.children.append(submenu)

            extra = getattr(model_admin, 'extra_menu_items', [])
            extra_func = getattr(model_admin, 'get_extra_menu_items', None)
            if extra_func:
                extra = extra_func(request)

            for item in extra:
                if len(item) == 2:
                    url, extra_title = item
                    weight = 1
                else:
                    url, extra_title, extra_group, weight = item
                    if extra_group not in menu:
                        menu[extra_group] = make_menu_group(extra_group)
                    group = menu[extra_group]

                submenu = make_menu_item(url=url,
                                         title=capfirst(extra_title),
                                         weight=weight)
                group.children.append(submenu)

    for title, submenu in menu.items():
        # sort the submenus by weight
        submenu.children.sort(key=lambda x: x.weight)
        for idx, sub in enumerate(submenu.children):
            if idx == 0:
                menu[title].url = sub.url
            if request.path == sub.url.split("?")[0]:
                sub.active = True
                menu[title].active = True
            if sub.url != '/' and request.path.startswith(sub.url):
                sub.active = True
            if sub.active:
                submenu.active = True

    # sort the menu by weight
    menu = OrderedDict(sorted(menu.items(), key=lambda x: x[1].weight))

    return menu
Пример #33
0
def render_menu_app_list(context):
    show_global_menu = sidebar_menu_setting()
    if not show_global_menu:
        return {'app_list': ''}

    if DJANGO_VERSION < (1, 8):
        dependencie = 'django.core.context_processors.request'
        processors = settings.TEMPLATE_CONTEXT_PROCESSORS
        dependency_str = 'settings.TEMPLATE_CONTEXT_PROCESSORS'
    else:
        dependencie = 'django.template.context_processors.request'
        implemented_engines = getattr(settings, 'BOOTSTRAP_ADMIN_ENGINES',
            ['django.template.backends.django.DjangoTemplates'])
        dependency_str = "the 'context_processors' 'OPTION' of one of the " + \
            "following engines: %s" % implemented_engines
        filtered_engines = [engine for engine in settings.TEMPLATES
            if engine['BACKEND'] in implemented_engines]
        if len(filtered_engines) == 0:
            raise ImproperlyConfigured(
                "bootstrap_admin: No compatible template engine found" +
                "bootstrap_admin requires one of the following engines: %s"
                % implemented_engines
            )
        processors = reduce(lambda x, y: x.extend(y), [
            engine.get('OPTIONS', {}).get('context_processors', [])
            for engine in filtered_engines])

    if dependencie not in processors:
        raise ImproperlyConfigured(
            "bootstrap_admin: in order to use the 'sidebar menu' requires" +
            " the '%s' to be added to %s"
            % (dependencie, dependency_str)
        )

    # Code adapted from django.contrib.admin.AdminSite
    app_dict = {}
    user = context.get('user')
    for model, model_admin in site._registry.items():
        app_label = model._meta.app_label
        has_module_perms = user.has_module_perms(app_label)

        if has_module_perms:
            perms = model_admin.get_model_perms(context.get('request'))

            # Check whether user has any perm for this module.
            # If so, add the module to the model_list.
            if True in perms.values():
                info = (app_label, model._meta.model_name)
                model_dict = {
                    'name': capfirst(model._meta.verbose_name_plural),
                    'object_name': model._meta.object_name,
                    'perms': perms,
                }
                if perms.get('change', False):
                    try:
                        model_dict['admin_url'] = reverse(
                            'admin:%s_%s_changelist' % info,
                            current_app=site.name
                        )
                    except NoReverseMatch:
                        pass
                if perms.get('add', False):
                    try:
                        model_dict['add_url'] = reverse(
                            'admin:%s_%s_add' % info,
                            current_app=site.name
                        )
                    except NoReverseMatch:
                        pass
                if app_label in app_dict:
                    app_dict[app_label]['models'].append(model_dict)
                else:
                    app_dict[app_label] = {
                        'name': apps.get_app_config(app_label).verbose_name,
                        'app_label': app_label,
                        'app_url': reverse(
                            'admin:app_list',
                            kwargs={'app_label': app_label},
                            current_app=site.name
                        ),
                        'has_module_perms': has_module_perms,
                        'models': [model_dict],
                    }

    # Sort the apps alphabetically.
    app_list = list(six.itervalues(app_dict))
    app_list.sort(key=lambda x: x['name'].lower())

    # Sort the models alphabetically within each sapp.
    for app in app_list:
        app['models'].sort(key=lambda x: x['name'])
    return {'app_list': app_list, 'current_url': context.get('request').path}
Пример #34
0
 def get_success_message(self, instance):
     return _("%(model_name)s '%(instance)s' updated.") % {
         'model_name': capfirst(self.verbose_name),
         'instance': instance
     }
Пример #35
0
 def get_page_subtitle(self):
     return capfirst(self.verbose_name)
Пример #36
0
 def get_page_title(self):
     return self.page_title or capfirst(self.opts.verbose_name_plural)
Пример #37
0
    PROJECTED_INVOICES = "PROJECTED_INVOICES"
    WORKING_TIME_CORRECTION = "WORKING_TIME_CORRECTION"


LABELS = {
    FEATURES.AWT_WARNING_INDIVIDUAL: {
        "label": _("Individual annual working time warning"),
    },
    FEATURES.AWT_WARNING_ALL: {
        "label": _("Annual working time warnings for all"),
    },
    FEATURES.BOOKKEEPING: {
        "label": _("Bookkeeping"),
    },
    FEATURES.BREAKS_NAG: {
        "label": capfirst(_("Breaks nag")),
        "help_text":
        _("Warn if user is taking an insufficient amount of breaks."),
    },
    FEATURES.CAMPAIGNS: {
        "label": capfirst(_("campaigns")),
        "help_text": _("Campaigns allow grouping projects."),
    },
    FEATURES.COFFEE: {
        "label": _("Coffee break"),
        "help_text": _("Receive regular invites for a coffee break?"),
    },
    FEATURES.CONTROLLING: {
        "label": _("Controlling"),
    },
    FEATURES.DEALS: {
Пример #38
0
    def _build_app_dict(self, request, label=None):
        """
        Build the app dictionary. The optional `label` parameter filters models
        of a specific app.
        """
        app_dict = {}

        if label:
            models = {
                m: m_a
                for m, m_a in self._registry.items()
                if m._meta.app_label == label
            }
        else:
            models = self._registry

        for model, model_admin in models.items():
            app_label = model._meta.app_label

            has_module_perms = model_admin.has_module_permission(request)
            if not has_module_perms:
                continue

            perms = model_admin.get_model_perms(request)

            # Check whether user has any perm for this module.
            # If so, add the module to the model_list.
            if True not in perms.values():
                continue

            info = (app_label, model._meta.model_name)
            model_dict = {
                'name': capfirst(model._meta.verbose_name_plural),
                'object_name': model._meta.object_name,
                'perms': perms,
                'admin_url': None,
                'add_url': None,
            }
            if perms.get('change') or perms.get('view'):
                model_dict['view_only'] = not perms.get('change')
                try:
                    model_dict['admin_url'] = reverse(
                        'admin:%s_%s_changelist' % info, current_app=self.name)
                except NoReverseMatch:
                    pass
            if perms.get('add'):
                try:
                    model_dict['add_url'] = reverse('admin:%s_%s_add' % info,
                                                    current_app=self.name)
                except NoReverseMatch:
                    pass

            if app_label in app_dict:
                app_dict[app_label]['models'].append(model_dict)
            else:
                app_dict[app_label] = {
                    'name':
                    apps.get_app_config(app_label).verbose_name,
                    'app_label':
                    app_label,
                    'app_url':
                    reverse(
                        'admin:app_list',
                        kwargs={'app_label': app_label},
                        current_app=self.name,
                    ),
                    'has_module_perms':
                    has_module_perms,
                    'models': [model_dict],
                }

        if label:
            return app_dict.get(label)
        return app_dict
Пример #39
0
 def set_name(self, name):
     self.name = name
     if not self.meta.label:
         self.label = capfirst(force_text(name).replace('_', ' '))
Пример #40
0
def get_app_list(context, order=True):
    admin_site = get_admin_site(context)
    request = context['request']

    app_dict = {}
    for model, model_admin in admin_site._registry.items():
        app_label = model._meta.app_label
        try:
            has_module_perms = model_admin.has_module_permission(request)
        except AttributeError:
            has_module_perms = request.user.has_module_perms(
                app_label)  # Fix Django < 1.8 issue

        if has_module_perms:
            perms = model_admin.get_model_perms(request)

            # Check whether user has any perm for this module.
            # If so, add the module to the model_list.
            if True in perms.values():
                info = (app_label, model._meta.model_name)
                model_dict = {
                    'name': capfirst(model._meta.verbose_name_plural),
                    'object_name': model._meta.object_name,
                    'perms': perms,
                }
                if perms.get('change', False):
                    try:
                        model_dict['admin_url'] = reverse(
                            'admin:%s_%s_changelist' % info,
                            current_app=admin_site.name)
                    except NoReverseMatch:
                        pass
                if perms.get('add', False):
                    try:
                        model_dict['add_url'] = reverse(
                            'admin:%s_%s_add' % info,
                            current_app=admin_site.name)
                    except NoReverseMatch:
                        pass
                if app_label in app_dict:
                    app_dict[app_label]['models'].append(model_dict)
                else:
                    try:
                        name = apps.get_app_config(app_label).verbose_name
                    except NameError:
                        name = app_label.title()
                    app_dict[app_label] = {
                        'name':
                        name,
                        'app_label':
                        app_label,
                        'app_url':
                        reverse(
                            'admin:app_list',
                            kwargs={'app_label': app_label},
                            current_app=admin_site.name,
                        ),
                        'has_module_perms':
                        has_module_perms,
                        'models': [model_dict],
                    }

    # Sort the apps alphabetically.
    app_list = list(app_dict.values())

    if order:
        app_list.sort(key=lambda x: x['name'].lower())

        # Sort the models alphabetically within each app.
        for app in app_list:
            app['models'].sort(key=lambda x: x['name'])

    return app_list
Пример #41
0
def get_deleted_objects(deleted_objects,
                        perms_needed,
                        user,
                        obj,
                        opts,
                        current_depth,
                        admin_site,
                        levels_to_root=4):
    """
    Helper function that recursively populates deleted_objects.

    `levels_to_root` defines the number of directories (../) to reach the
    admin root path. In a change_view this is 4, in a change_list view 2.

    This is for backwards compatibility since the options.delete_selected
    method uses this function also from a change_list view.
    This will not be used if we can reverse the URL.
    """
    nh = _nest_help  # Bind to local variable for performance
    if current_depth > 16:
        return  # Avoid recursing too deep.
    opts_seen = []
    for related in opts.get_all_related_objects():
        has_admin = related.model in admin_site._registry
        if related.opts in opts_seen:
            continue
        opts_seen.append(related.opts)
        rel_opts_name = related.get_accessor_name()
        if isinstance(related.field.rel, models.OneToOneRel):
            try:
                sub_obj = getattr(obj, rel_opts_name)
            except ObjectDoesNotExist:
                pass
            else:
                if has_admin:
                    p = '%s.%s' % (related.opts.app_label,
                                   related.opts.get_delete_permission())
                    if not user.has_perm(p):
                        perms_needed.add(related.opts.verbose_name)
                        # We don't care about populating deleted_objects now.
                        continue
                if not has_admin:
                    # Don't display link to edit, because it either has no
                    # admin or is edited inline.
                    nh(deleted_objects, current_depth, [
                        u'%s: %s' % (capfirst(related.opts.verbose_name),
                                     force_unicode(sub_obj)), []
                    ])
                else:
                    # Display a link to the admin page.
                    nh(deleted_objects, current_depth, [
                        mark_safe(u'%s: <a href="%s">%s</a>' %
                                  (escape(capfirst(related.opts.verbose_name)),
                                   get_change_view_url(
                                       related.opts.app_label,
                                       related.opts.object_name.lower(),
                                       sub_obj._get_pk_val(), admin_site,
                                       levels_to_root), escape(sub_obj))), []
                    ])
                get_deleted_objects(deleted_objects, perms_needed, user,
                                    sub_obj, related.opts, current_depth + 2,
                                    admin_site)
        else:
            has_related_objs = False
            for sub_obj in getattr(obj, rel_opts_name).all():
                has_related_objs = True
                if not has_admin:
                    # Don't display link to edit, because it either has no
                    # admin or is edited inline.
                    nh(deleted_objects, current_depth, [
                        u'%s: %s' % (capfirst(related.opts.verbose_name),
                                     force_unicode(sub_obj)), []
                    ])
                else:
                    # Display a link to the admin page.
                    nh(deleted_objects, current_depth, [
                        mark_safe(u'%s: <a href="%s">%s</a>' %
                                  (escape(capfirst(related.opts.verbose_name)),
                                   get_change_view_url(
                                       related.opts.app_label,
                                       related.opts.object_name.lower(),
                                       sub_obj._get_pk_val(), admin_site,
                                       levels_to_root), escape(sub_obj))), []
                    ])
                get_deleted_objects(deleted_objects, perms_needed, user,
                                    sub_obj, related.opts, current_depth + 2,
                                    admin_site)
            # If there were related objects, and the user doesn't have
            # permission to delete them, add the missing perm to perms_needed.
            if has_admin and has_related_objs:
                p = '%s.%s' % (related.opts.app_label,
                               related.opts.get_delete_permission())
                if not user.has_perm(p):
                    perms_needed.add(related.opts.verbose_name)
    for related in opts.get_all_related_many_to_many_objects():
        has_admin = related.model in admin_site._registry
        if related.opts in opts_seen:
            continue
        opts_seen.append(related.opts)
        rel_opts_name = related.get_accessor_name()
        has_related_objs = False

        # related.get_accessor_name() could return None for symmetrical relationships
        if rel_opts_name:
            rel_objs = getattr(obj, rel_opts_name, None)
            if rel_objs:
                has_related_objs = True

        if has_related_objs:
            for sub_obj in rel_objs.all():
                if not has_admin:
                    # Don't display link to edit, because it either has no
                    # admin or is edited inline.
                    nh(deleted_objects, current_depth, [_('One or more %(fieldname)s in %(name)s: %(obj)s') % \
                        {'fieldname': force_unicode(related.field.verbose_name), 'name': force_unicode(related.opts.verbose_name), 'obj': escape(sub_obj)}, []])
                else:
                    # Display a link to the admin page.
                    nh(deleted_objects, current_depth, [
                        mark_safe((_('One or more %(fieldname)s in %(name)s:') % {'fieldname': escape(force_unicode(related.field.verbose_name)), 'name': escape(force_unicode(related.opts.verbose_name))}) + \
                        (u' <a href="%s">%s</a>' % \
                            (get_change_view_url(related.opts.app_label,
                                                 related.opts.object_name.lower(),
                                                 sub_obj._get_pk_val(),
                                                 admin_site,
                                                 levels_to_root),
                            escape(sub_obj)))), []])
        # If there were related objects, and the user doesn't have
        # permission to change them, add the missing perm to perms_needed.
        if has_admin and has_related_objs:
            p = u'%s.%s' % (related.opts.app_label,
                            related.opts.get_change_permission())
            if not user.has_perm(p):
                perms_needed.add(related.opts.verbose_name)
Пример #42
0
def admin_app_list(request):
    """
    Adopted from ``django.contrib.admin.sites.AdminSite.index``.
    Returns a list of lists of models grouped and ordered according to
    ``mezzanine.conf.ADMIN_MENU_ORDER``. Called from the
    ``admin_dropdown_menu`` template tag as well as the ``app_list``
    dashboard widget.
    """
    app_dict = {}

    # Model or view --> (group index, group title, item index, item title).
    menu_order = {}
    for (group_index, group) in enumerate(settings.ADMIN_MENU_ORDER):
        group_title, items = group
        for (item_index, item) in enumerate(items):
            if isinstance(item, (tuple, list)):
                item_title, item = item
            else:
                item_title = None
            menu_order[item] = (group_index, group_title, item_index,
                                item_title)

    # Add all registered models, using group and title from menu order.
    for (model, model_admin) in admin.site._registry.items():
        opts = model._meta
        in_menu = not hasattr(model_admin, "in_menu") or model_admin.in_menu()
        if in_menu and request.user.has_module_perms(opts.app_label):
            perms = model_admin.get_model_perms(request)
            admin_url_name = ""
            if perms["change"]:
                admin_url_name = "changelist"
                change_url = admin_url(model, admin_url_name)
            else:
                change_url = None
            if perms["add"]:
                admin_url_name = "add"
                add_url = admin_url(model, admin_url_name)
            else:
                add_url = None
            if admin_url_name:
                model_label = "%s.%s" % (opts.app_label, opts.object_name)
                try:
                    app_index, app_title, model_index, model_title = \
                        menu_order[model_label]
                except KeyError:
                    app_index = None
                    app_title = opts.app_config.verbose_name.title()
                    model_index = None
                    model_title = None
                else:
                    del menu_order[model_label]

                if not model_title:
                    model_title = capfirst(model._meta.verbose_name_plural)

                if app_title not in app_dict:
                    app_dict[app_title] = {
                        "index": app_index,
                        "name": app_title,
                        "models": [],
                    }
                app_dict[app_title]["models"].append({
                    "index":
                    model_index,
                    "perms":
                    model_admin.get_model_perms(request),
                    "name":
                    model_title,
                    "admin_url":
                    change_url,
                    "add_url":
                    add_url
                })

    # Menu may also contain view or url pattern names given as (title, name).
    for (item_url, item) in menu_order.items():
        app_index, app_title, item_index, item_title = item
        try:
            item_url = reverse(item_url)
        except NoReverseMatch:
            continue
        if app_title not in app_dict:
            app_dict[app_title] = {
                "index": app_index,
                "name": app_title,
                "models": [],
            }
        app_dict[app_title]["models"].append({
            "index": item_index,
            "perms": {
                "custom": True
            },
            "name": item_title,
            "admin_url": item_url,
        })

    app_list = list(app_dict.values())
    sort = lambda x: (x["index"] if x["index"] is not None else 999, x["name"])
    for app in app_list:
        app["models"].sort(key=sort)
    app_list.sort(key=sort)
    return app_list
Пример #43
0
    def get_nav_menu(self):
        site_menu = list(self.get_site_menu() or [])
        had_urls = []

        def get_url(menu, had_urls):
            if 'url' in menu:
                had_urls.append(menu['url'])
            if 'menus' in menu:
                for m in menu['menus']:
                    get_url(m, had_urls)

        get_url({'menus': site_menu}, had_urls)

        nav_menu = OrderedDict()

        # 添加
        menus_ = self.admin_site._registry.items()
        for model, model_admin in self.admin_site._registry.items():
            if getattr(model_admin, 'hidden_menu', False):
                continue
            app_label = model._meta.app_label
            app_icon = None
            model_dict = {
                'title': smart_text(capfirst(model._meta.verbose_name_plural)),
                'url': self.get_model_url(model, "changelist"),
                'icon': self.get_model_icon(model),
                'perm': self.get_model_perm(model, 'view'),
                'order': model_admin.order,
            }
            if model_dict['url'] in had_urls:
                continue

            app_key = "app:%s" % app_label
            if app_key in nav_menu:
                nav_menu[app_key]['menus'].append(model_dict)
            else:
                # Find app title
                app_title = smart_text(app_label.title())
                if app_label.lower() in self.apps_label_title:
                    app_title = self.apps_label_title[app_label.lower()]
                else:
                    app_title = smart_text(
                        apps.get_app_config(app_label).verbose_name)
                # find app icon
                if app_label.lower() in self.apps_icons:
                    app_icon = self.apps_icons[app_label.lower()]

                # 隐藏
                # nav_menu[app_key] = {
                #     'title': app_title,
                #     'menus': [model_dict],
                # }

                else:
                    appL = apps.get_app_config(app_label)
                    app_title = smart_text(
                        apps.get_app_config(app_label).verbose_name)
                    # added by Fiona for menu ordering
                    if app_label == "auth":
                        app_index = len(menus_) - 1
                    elif app_label == "xadmin":
                        app_index = len(menus_) - 2
                    else:
                        app_index = appL.orderIndex
                # find app icon
                if app_label.lower() in self.apps_icons:
                    app_icon = self.apps_icons[app_label.lower()]
                nav_menu[app_key] = {
                    "orderIndex": app_index,
                    'title': app_title,
                    'menus': [model_dict],
                }

            app_menu = nav_menu[app_key]
            if app_icon:
                app_menu['first_icon'] = app_icon
            elif ('first_icon' not in app_menu or app_menu['first_icon']
                  == self.default_model_icon) and model_dict.get('icon'):
                app_menu['first_icon'] = model_dict['icon']

            if 'first_url' not in app_menu and model_dict.get('url'):
                app_menu['first_url'] = model_dict['url']

        for menu in nav_menu.values():
            menu['menus'].sort(key=sortkeypicker(['order', 'title']))

        nav_menu = list(nav_menu.values())
        # nav_menu.sort(key=lambda x: x['title']) 隐藏

        # 左侧菜单自定义排序新增
        nav_menu.sort(key=sortkeypicker(['orderIndex']))

        site_menu.extend(nav_menu)

        return site_menu
Пример #44
0
def date_hierarchy(cl):
    """
    Displays the date hierarchy for date drill-down functionality.
    """
    if cl.date_hierarchy:
        field_name = cl.date_hierarchy
        field = get_fields_from_path(cl.model, field_name)[-1]
        dates_or_datetimes = 'datetimes' if isinstance(field, models.DateTimeField) else 'dates'
        year_field = '%s__year' % field_name
        month_field = '%s__month' % field_name
        day_field = '%s__day' % field_name
        field_generic = '%s__' % field_name
        year_lookup = cl.params.get(year_field)
        month_lookup = cl.params.get(month_field)
        day_lookup = cl.params.get(day_field)

        def link(filters):
            return cl.get_query_string(filters, [field_generic])

        if not (year_lookup or month_lookup or day_lookup):
            # select appropriate start level
            date_range = cl.queryset.aggregate(first=models.Min(field_name),
                                               last=models.Max(field_name))
            if date_range['first'] and date_range['last']:
                if date_range['first'].year == date_range['last'].year:
                    year_lookup = date_range['first'].year
                    if date_range['first'].month == date_range['last'].month:
                        month_lookup = date_range['first'].month

        if year_lookup and month_lookup and day_lookup:
            day = datetime.date(int(year_lookup), int(month_lookup), int(day_lookup))
            return {
                'show': True,
                'back': {
                    'link': link({year_field: year_lookup, month_field: month_lookup}),
                    'title': capfirst(formats.date_format(day, 'YEAR_MONTH_FORMAT'))
                },
                'choices': [{'title': capfirst(formats.date_format(day, 'MONTH_DAY_FORMAT'))}]
            }
        elif year_lookup and month_lookup:
            days = cl.queryset.filter(**{year_field: year_lookup, month_field: month_lookup})
            days = getattr(days, dates_or_datetimes)(field_name, 'day')
            return {
                'show': True,
                'back': {
                    'link': link({year_field: year_lookup}),
                    'title': str(year_lookup)
                },
                'choices': [{
                    'link': link({year_field: year_lookup, month_field: month_lookup, day_field: day.day}),
                    'title': capfirst(formats.date_format(day, 'MONTH_DAY_FORMAT'))
                } for day in days]
            }
        elif year_lookup:
            months = cl.queryset.filter(**{year_field: year_lookup})
            months = getattr(months, dates_or_datetimes)(field_name, 'month')
            return {
                'show': True,
                'back': {
                    'link': link({}),
                    'title': _('All dates')
                },
                'choices': [{
                    'link': link({year_field: year_lookup, month_field: month.month}),
                    'title': capfirst(formats.date_format(month, 'YEAR_MONTH_FORMAT'))
                } for month in months]
            }
        else:
            years = getattr(cl.queryset, dates_or_datetimes)(field_name, 'year')
            return {
                'show': True,
                'choices': [{
                    'link': link({year_field: str(year.year)}),
                    'title': str(year.year),
                } for year in years]
            }
Пример #45
0
class Person(models.Model):
    """
    Tabla para persons
    """
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)

    national_id_doc = models.CharField(
        capfirst(_('national identity document')),
        max_length=20,
        null=True,
        blank=True)  # extend person documents in DocumentPersonType

    first_name = models.CharField(
        capfirst(_('first name')),
        max_length=50,
        help_text=_('primer nombre'),
    )
    other_names = models.CharField(
        capfirst(_('other names')),
        max_length=50,
        null=True,
        blank=True,
        help_text=_('otros nombres'),
    )
    last_name = models.CharField(
        capfirst(_('last name')),
        max_length=50,
        null=True,
        blank=True,
        help_text=_('apellido paterno'),
    )
    mother_last_name = models.CharField(
        capfirst(_('mother\'s last name')),
        max_length=50,
        null=True,
        blank=True,
        help_text=_('apellido materno'),
    )
    birth_date = models.DateField(_('birth date'), null=True, blank=True)
    photo = models.ImageField(
        capfirst(_('photo')),
        upload_to='persons',
        default='persons/default.png',
        null=True,
        blank=True,
    )

    created_at = models.DateTimeField(_('created at'), auto_now_add=True)
    updated_at = models.DateTimeField(_('updated at'),
                                      auto_now=True,
                                      blank=True,
                                      null=True)
    registered_by = models.TextField(blank=True, null=True)

    # colocar debajo tus nuevos campos

    class Meta:
        verbose_name = capfirst(_('person'))
        verbose_name_plural = capfirst(_('persons'))
        '''
        unique_together = (
            ('first_name', 'other_names', 'last_name', 'mother_last_name',
                'national_id_doc'),
            ('national_id_doc'),
        )
        '''

    def __str__(self):
        return '%s %s %s (%s)' % (self.first_name, self.last_name,
                                  self.mother_last_name, self.national_id_doc)
Пример #46
0
    def _build_app_statistic(self, request, label=None):
        statistic_dict = {}

        if label:
            models = {
                m: m_a
                for m, m_a in self._registry.items()
                if m._meta.app_label == label
            }
        else:
            models = self._registry

        for model, model_admin in models.items():
            app_label = model._meta.app_label

            has_module_perms = model_admin.has_module_permission(request)
            if not has_module_perms:
                continue

            perms = model_admin.get_model_perms(request)

            # Check whether user has any perm for this module.
            # If so, add the module to the model_list.
            if True not in perms.values():
                continue

            info = (app_label, model._meta.model_name)
            model_dict = {
                'name': capfirst(model._meta.verbose_name_plural),
                'order': 0,
                'perms': perms,
                'total': model.objects.count(),
                'object_name': model._meta.object_name,
                'admin_url': None,
            }

            if hasattr(model, 'vueAdmin_order'):
                model_dict['order'] = model.vueAdmin_order()

            if perms.get('change') or perms.get('view'):
                model_dict['view_only'] = not perms.get('change')
                try:
                    model_dict['admin_url'] = reverse(
                        'admin:%s_%s_changelist' % info, current_app=self.name)
                except NoReverseMatch:
                    pass

            if app_label in statistic_dict:
                statistic_dict[app_label]['models'].append(model_dict)
            else:
                statistic_dict[app_label] = {
                    'key': apps.get_app_config(app_label).name,
                    'name': apps.get_app_config(app_label).verbose_name,
                    'icon': apps.get_app_config(app_label).vueAdmin_icon,
                    'order': apps.get_app_config(app_label).vueAdmin_order,
                    'app_label': app_label,
                    'has_module_perms': has_module_perms,
                    'models': [model_dict],
                }
        if label:
            return statistic_dict.get(label)

        return statistic_dict
Пример #47
0
def changes(model, fields, actions):
    changes = []

    if not actions:
        return changes

    users = {u.pk: u.get_full_name() for u in User.objects.all()}
    users[0] = _("<anonymous>")
    fields = [
        f for f in model._meta.get_fields()
        if hasattr(f, "attname") and not f.primary_key and f.name in fields
    ]

    prettifier = Prettifier()

    for action in actions:
        if action.action == "I":
            values = action.row_data
            version_changes = [
                mark_safe(
                    _("Initial value of '%(field)s' was '%(current)s'.") % {
                        "field":
                        conditional_escape(capfirst(f.verbose_name)),
                        "current":
                        conditional_escape(prettifier.format(values, f)),
                    }) for f in fields if f.attname in values
            ]

        elif action.action == "U":
            values = action.changed_fields or {}
            version_changes = [
                mark_safe(
                    _("New value of '%(field)s' was '%(current)s'.") % {
                        "field":
                        conditional_escape(capfirst(f.verbose_name)),
                        "current":
                        conditional_escape(prettifier.format(values, f)),
                    }) for f in fields if f.attname in values
            ]

        else:  # Deletion or truncation
            values = action.row_data
            version_changes = [
                mark_safe(
                    _("Final value of '%(field)s' was '%(current)s'.") % {
                        "field":
                        conditional_escape(capfirst(f.verbose_name)),
                        "current":
                        conditional_escape(prettifier.format(values, f)),
                    }) for f in fields if f.attname in values
            ]

        if version_changes:
            changes.append(
                Change(
                    changes=version_changes,
                    created_at=action.created_at,
                    pretty_user_name=users.get(action.user_id)
                    or action.user_name,
                    values={
                        f.attname: values.get(f.attname)
                        for f in fields if f.attname in values
                    },
                    version=action,
                ))

    return changes
Пример #48
0
 class Meta:
     verbose_name = capfirst(_('person'))
     verbose_name_plural = capfirst(_('persons'))
     '''
def get_field_kwargs(field_name, model_field):
    """
    Creates a default instance of a basic non-relational field.
    """
    kwargs = {}
    validator_kwarg = list(model_field.validators)

    # The following will only be used by ModelField classes.
    # Gets removed for everything else.
    kwargs['model_field'] = model_field

    if model_field.verbose_name and needs_label(model_field, field_name):
        kwargs['label'] = capfirst(model_field.verbose_name)

    if model_field.help_text:
        kwargs['help_text'] = model_field.help_text

    max_digits = getattr(model_field, 'max_digits', None)
    if max_digits is not None:
        kwargs['max_digits'] = max_digits

    decimal_places = getattr(model_field, 'decimal_places', None)
    if decimal_places is not None:
        kwargs['decimal_places'] = decimal_places

    if isinstance(model_field, models.TextField):
        kwargs['style'] = {'base_template': 'textarea.html'}

    if isinstance(model_field, models.AutoField) or not model_field.editable:
        # If this field is read-only, then return early.
        # Further keyword arguments are not valid.
        kwargs['read_only'] = True
        return kwargs

    if model_field.has_default() or model_field.blank or model_field.null:
        kwargs['required'] = False

    if model_field.null and not isinstance(model_field,
                                           models.NullBooleanField):
        kwargs['allow_null'] = True

    if model_field.blank and (isinstance(model_field, models.CharField)
                              or isinstance(model_field, models.TextField)):
        kwargs['allow_blank'] = True

    if model_field.choices:
        # If this model field contains choices, then return early.
        # Further keyword arguments are not valid.
        kwargs['choices'] = model_field.choices
        return kwargs

    # Our decimal validation is handled in the field code, not validator code.
    # (In Django 1.9+ this differs from previous style)
    if isinstance(model_field, models.DecimalField):
        validator_kwarg = [
            validator for validator in validator_kwarg
            if not isinstance(validator, validators.DecimalValidator)
        ]

    # Ensure that max_length is passed explicitly as a keyword arg,
    # rather than as a validator.
    max_length = getattr(model_field, 'max_length', None)
    if max_length is not None and isinstance(model_field, models.CharField):
        kwargs['max_length'] = max_length
        validator_kwarg = [
            validator for validator in validator_kwarg
            if not isinstance(validator, validators.MaxLengthValidator)
        ]

    # Ensure that min_length is passed explicitly as a keyword arg,
    # rather than as a validator.
    min_length = next(
        (validator.limit_value for validator in validator_kwarg
         if isinstance(validator, validators.MinLengthValidator)), None)
    if min_length is not None and isinstance(model_field, models.CharField):
        kwargs['min_length'] = min_length
        validator_kwarg = [
            validator for validator in validator_kwarg
            if not isinstance(validator, validators.MinLengthValidator)
        ]

    # Ensure that max_value is passed explicitly as a keyword arg,
    # rather than as a validator.
    max_value = next((validator.limit_value for validator in validator_kwarg
                      if isinstance(validator, validators.MaxValueValidator)),
                     None)
    if max_value is not None and isinstance(model_field, NUMERIC_FIELD_TYPES):
        kwargs['max_value'] = max_value
        validator_kwarg = [
            validator for validator in validator_kwarg
            if not isinstance(validator, validators.MaxValueValidator)
        ]

    # Ensure that max_value is passed explicitly as a keyword arg,
    # rather than as a validator.
    min_value = next((validator.limit_value for validator in validator_kwarg
                      if isinstance(validator, validators.MinValueValidator)),
                     None)
    if min_value is not None and isinstance(model_field, NUMERIC_FIELD_TYPES):
        kwargs['min_value'] = min_value
        validator_kwarg = [
            validator for validator in validator_kwarg
            if not isinstance(validator, validators.MinValueValidator)
        ]

    # URLField does not need to include the URLValidator argument,
    # as it is explicitly added in.
    if isinstance(model_field, models.URLField):
        validator_kwarg = [
            validator for validator in validator_kwarg
            if not isinstance(validator, validators.URLValidator)
        ]

    # EmailField does not need to include the validate_email argument,
    # as it is explicitly added in.
    if isinstance(model_field, models.EmailField):
        validator_kwarg = [
            validator for validator in validator_kwarg
            if validator is not validators.validate_email
        ]

    # SlugField do not need to include the 'validate_slug' argument,
    if isinstance(model_field, models.SlugField):
        validator_kwarg = [
            validator for validator in validator_kwarg
            if validator is not validators.validate_slug
        ]

    # IPAddressField do not need to include the 'validate_ipv46_address' argument,
    if isinstance(model_field, models.GenericIPAddressField):
        validator_kwarg = [
            validator for validator in validator_kwarg
            if validator is not validators.validate_ipv46_address
        ]

    if getattr(model_field, 'unique', False):
        unique_error_message = model_field.error_messages.get('unique', None)
        if unique_error_message:
            unique_error_message = unique_error_message % {
                'model_name': model_field.model._meta.object_name,
                'field_label': model_field.verbose_name
            }
        validator = UniqueValidator(
            queryset=model_field.model._default_manager,
            message=unique_error_message)
        validator_kwarg.append(validator)

    if validator_kwarg:
        kwargs['validators'] = validator_kwarg

    return kwargs
Пример #50
0
def delete_selected(modeladmin, request, queryset):
    """
    Default action which deletes the selected objects.

    This action first displays a confirmation page whichs shows all the
    deleteable objects, or, if the user has no permission one of the related
    childs (foreignkeys), a "permission denied" message.

    Next, it delets all selected objects and redirects back to the change list.
    """
    opts = modeladmin.model._meta
    app_label = opts.app_label

    # Check that the user has delete permission for the actual model
    if not modeladmin.has_delete_permission(request):
        raise PermissionDenied

    # Populate deletable_objects, a data structure of all related objects that
    # will also be deleted.

    # deletable_objects must be a list if we want to use '|unordered_list' in the template
    deletable_objects = []
    perms_needed = set()
    i = 0
    for obj in queryset:
        deletable_objects.append([
            mark_safe(u'%s: <a href="%s/">%s</a>' %
                      (escape(force_unicode(capfirst(
                          opts.verbose_name))), obj.pk, escape(obj))), []
        ])
        get_deleted_objects(deletable_objects[i],
                            perms_needed,
                            request.user,
                            obj,
                            opts,
                            1,
                            modeladmin.admin_site,
                            levels_to_root=2)
        i = i + 1

    # The user has already confirmed the deletion.
    # Do the deletion and return a None to display the change list view again.
    if request.POST.get('post'):
        if perms_needed:
            raise PermissionDenied
        n = queryset.count()
        if n:
            for obj in queryset:
                obj_display = force_unicode(obj)
                modeladmin.log_deletion(request, obj, obj_display)
            queryset.delete()
            modeladmin.message_user(
                request,
                _("Successfully deleted %(count)d %(items)s.") % {
                    "count": n,
                    "items": model_ngettext(modeladmin.opts, n)
                })
        # Return None to display the change list page again.
        return None

    context = {
        "title": _("Are you sure?"),
        "object_name": force_unicode(opts.verbose_name),
        "deletable_objects": deletable_objects,
        'queryset': queryset,
        "perms_lacking": perms_needed,
        "opts": opts,
        "root_path": modeladmin.admin_site.root_path,
        "app_label": app_label,
        'action_checkbox_name': helpers.ACTION_CHECKBOX_NAME,
    }

    # Display the confirmation page
    return render_to_response(
        modeladmin.delete_confirmation_template or [
            "admin/%s/%s/delete_selected_confirmation.html" %
            (app_label, opts.object_name.lower()),
            "admin/%s/delete_selected_confirmation.html" % app_label,
            "admin/delete_selected_confirmation.html"
        ],
        context,
        context_instance=template.RequestContext(request))
Пример #51
0
    def app_index(self, request, app_label, extra_context=None):
        user = request.user
        app_name = apps.get_app_config(app_label).verbose_name
        has_module_perms = user.has_module_perms(app_label)
        if not has_module_perms:
            raise PermissionDenied
        app_dict = {}
        for model, model_admin in self._registry.items():
            if app_label == model._meta.app_label:
                perms = model_admin.get_model_perms(request)

                # Check whether user has any perm for this module.
                # If so, add the module to the model_list.
                if True in perms.values():
                    info = (app_label, model._meta.model_name)
                    model_dict = {
                        'name': capfirst(model._meta.verbose_name_plural),
                        'object_name': model._meta.object_name,
                        'perms': perms,
                    }
                    if perms.get('change'):
                        try:
                            model_dict['admin_url'] = reverse(
                                'admin:%s_%s_changelist' % info,
                                current_app=self.name)
                        except NoReverseMatch:
                            pass
                    if perms.get('add'):
                        try:
                            model_dict['add_url'] = reverse(
                                'admin:%s_%s_add' % info,
                                current_app=self.name)
                        except NoReverseMatch:
                            pass
                    if app_dict:
                        app_dict['models'].append(model_dict),
                    else:
                        # First time around, now that we know there's
                        # something to display, add in the necessary meta
                        # information.
                        app_dict = {
                            'name': app_name,
                            'app_label': app_label,
                            'app_url': '',
                            'has_module_perms': has_module_perms,
                            'models': [model_dict],
                        }
        if not app_dict:
            raise Http404('The requested admin page does not exist.')
        # Sort the models alphabetically within each app.
        app_dict['models'].sort(key=lambda x: x['name'])
        context = dict(
            self.each_context(),
            title=_('%(app)s administration') % {'app': app_name},
            app_list=[app_dict],
            app_label=app_label,
        )
        context.update(extra_context or {})

        return TemplateResponse(
            request,
            self.app_index_template
            or ['admin/%s/app_index.html' % app_label, 'admin/app_index.html'],
            context,
            current_app=self.name)
Пример #52
0
class User(AbstractUser):
  languageList = tuple( [ ('auto', _('Detect automatically')), ] + list(settings.LANGUAGES) )
  language = models.CharField(
    _('language'), max_length=10, choices=languageList,
    default='auto'
    )
  theme = models.CharField(
    _('theme'), max_length=20, default=settings.DEFAULT_THEME,
    choices=[ (i, capfirst(i)) for i in settings.THEMES ]
    )
  pagesize = models.PositiveIntegerField(_('page size'), default=settings.DEFAULT_PAGESIZE)
  horizonbuckets = models.CharField(max_length=300, blank=True, null=True)
  horizonstart = models.DateTimeField(blank=True, null=True)
  horizonend = models.DateTimeField(blank=True, null=True)
  horizontype = models.BooleanField(blank=True, default=True)
  horizonlength = models.IntegerField(blank=True, default=6, null=True)
  horizonunit = models.CharField(
    blank=True, max_length=5, default='month', null=True,
    choices=(("day", "day"), ("week", "week"), ("month", "month"))
    )
  lastmodified = models.DateTimeField(
    _('last modified'), auto_now=True, null=True, blank=True,
    editable=False, db_index=True
    )


  def save(self, force_insert=False, force_update=False, using=DEFAULT_DB_ALIAS, update_fields=None):
    '''
    Every change to a user model is saved to all active scenarios.

    The is_superuser and is_active fields can be different in each scenario.
    All other fields are expected to be identical in each database.

    Because of the logic in this method creating users directly in the
    database tables is NOT a good idea!
    '''
    # We want to automatically give access to the django admin to all users
    self.is_staff = True

    scenarios = [
      i['name']
      for i in Scenario.objects.using(DEFAULT_DB_ALIAS).filter(status='In use').values('name')
      if i['name'] in settings.DATABASES
      ]

    # The same id of a new user MUST be identical in all databases.
    # We manipulate the sequences, and correct if required.
    newuser = False
    tmp_is_active = self.is_active
    tmp_is_superuser = self.is_superuser
    if self.id is None:
      newuser = True
      self.id = 0
      cur_seq = {}
      for db in scenarios:
        cursor = connections[db].cursor()
        cursor.execute("select nextval('common_user_id_seq')")
        cur_seq[db] = cursor.fetchone()[0]
        if cur_seq[db] > self.id:
          self.id = cur_seq[db]
      for db in scenarios:
        if cur_seq[db] != self.id:
          cursor = connections[db].cursor()
          cursor.execute("select setval('common_user_id_seq', %s)", [self.id - 1])
      self.is_active = False
      self.is_superuser = False

    # Save only specific fields which we want to have identical across
    # all scenario databases.
    if not update_fields:
      update_fields2 = [
        'username', 'password', 'last_login', 'first_name', 'last_name',
        'email', 'date_joined', 'language', 'theme', 'pagesize',
        'horizonbuckets', 'horizonstart', 'horizonend', 'horizonunit',
        'lastmodified', 'is_staff'
        ]
    else:
      # Important is NOT to save the is_active and is_superuser fields.
      update_fields2 = update_fields[:]  # Copy!
      if 'is_active' in update_fields2:
        update_fields2.remove('is_active')
      if 'is_superuser' in update_fields:
        update_fields2.remove('is_superuser')
    if update_fields2 or newuser:
      for db in scenarios:
        if db == using:
          continue
        try:
          with transaction.atomic(using=db, savepoint=True):
            super(User, self).save(
              force_insert=force_insert,
              force_update=force_update,
              using=db,
              update_fields=update_fields2 if not newuser else None
              )
        except:
          try:
            with transaction.atomic(using=db, savepoint=False):
              newuser = True
              self.is_active = False
              self.is_superuser = False
              super(User, self).save(
                force_insert=force_insert,
                force_update=force_update,
                using=db
                )
              if settings.DEFAULT_USER_GROUP:
                grp = Group.objects.all().using(db).get_or_create(name=settings.DEFAULT_USER_GROUP)[0]
                self.groups.add(grp.id)
          except Exception as e:
            logger.warn("Can't save user '%s' in scenario '%s': %s" % (self.username, db, e))

    # Continue with the regular save, as if nothing happened.
    self.is_active = tmp_is_active
    self.is_superuser = tmp_is_superuser
    usr = super(User, self).save(
      force_insert=force_insert,
      force_update=force_update,
      using=using,
      update_fields=update_fields
      )
    if settings.DEFAULT_USER_GROUP and newuser:
      grp = Group.objects.all().using(using).get_or_create(name=settings.DEFAULT_USER_GROUP)[0]
      self.groups.add(grp.id)
    return usr


  def joined_age(self):
    '''
    Returns the number of days since the user joined
    '''
    if self.date_joined.year == 2000:
      # This is the user join date from the demo database.
      # We'll consider that a new user.
      self.date_joined = self.last_login
      self.save()
    return (datetime.now() - self.date_joined).total_seconds() / 86400


  class Meta:
    db_table = "common_user"
    # Translators: Translation included with Django
    verbose_name = _('user')
    # Translators: Translation included with Django
    verbose_name_plural = _('users')


  def getPreference(self, prop, default=None, database=DEFAULT_DB_ALIAS):
    try:
      result = None
      for p in UserPreference.objects.all().using(database).filter(property=prop).filter(Q(user__isnull=True) | Q(user=self.id)).order_by('-user').only('user', 'value'):
        if result:
          result.update(p.value)
        else:
          result = p.value
      return result if result else default
    except ValueError:
      logger.error("Invalid preference '%s' of user '%s'" % (prop, self.username))
      return default
    except:
      return default


  def setPreference(self, prop, val, database=DEFAULT_DB_ALIAS):
    if val is None:
      if prop in settings.GLOBAL_PREFERENCES and self.is_superuser:
        # Delete global preferences
        UserPreference.objects.all().using(database).filter(user__isnull=True, property=prop).delete()
      # Delete user preferences
      self.preferences.using(database).filter(user=self, property=prop).delete()
    else:
      if prop in settings.GLOBAL_PREFERENCES:
        val_global = { k: v for k, v in val.items() if k in settings.GLOBAL_PREFERENCES[prop] }
        val_user = { k: v for k, v in val.items() if k not in settings.GLOBAL_PREFERENCES[prop] }
        if val_global and self.is_superuser:
          # A superuser can save global preferences for this property
          recs = UserPreference.objects.all().using(database).filter(user__isnull=True, property=prop).update(value=val_global)
          if not recs:
            pref = UserPreference(user=None, property=prop, value=val_global)
            pref.save(using=database)
        if val_user:
          # Everyone can save his personal preferences for this property
          recs = UserPreference.objects.all().using(database).filter(user=self, property=prop).update(value=val_user)
          if not recs:
            pref = UserPreference(user=self, property=prop, value=val_user)
            pref.save(using=database)
      else:
        # No global preferences configured for this property
        recs = UserPreference.objects.all().using(database).filter(user=self, property=prop).update(value=val)
        if not recs:
          pref = UserPreference(user=self, property=prop, value=val)
          pref.save(using=database)


  def getMaxLoglevel(self, database=DEFAULT_DB_ALIAS):
    '''
    Return the maximum log level of the planning engine this user can activate.
    '''
    return 999
Пример #53
0
    def render(self, context):
        try:
            req = context["request"]
        except Exception:
            return ""  # No request found in the context: no crumbs...
        if not hasattr(req, "session"):
            return  # No session found in the context: no crumbs...

        # Pick up the current crumbs from the session cookie
        try:
            cur = req.session["crumbs"]
            try:
                cur = cur[req.prefix]
            except Exception:
                cur = []
        except Exception:
            req.session["crumbs"] = {}
            cur = []

        # Compute the new crumb node
        count = 0
        try:
            title = variable_title.resolve(context)
        except Exception:
            title = req.get_full_path()
        if title != _("cockpit"):
            # Don't handle the cockpit screen in the crumbs
            try:
                # Check if the same title is already in the crumbs.
                title = str(title)
                exists = False
                for i in cur:
                    if i[0] == title:
                        # Current URL already exists in the list and we move it to the end
                        node = i
                        del cur[count]
                        cur.append((node[0], node[1], req.path))
                        exists = True
                        break
                    count += 1

                if not exists:
                    # Add the current URL to the stack
                    if "tour" in req.GET:
                        # Special case when the guided tour is used: we don't want to
                        # include the tour argument in the breadcrumb. It makes the
                        # breadcrumb link reenter the tour, which is not cool.
                        params = req.GET.copy()
                        params.pop("tour")
                        cur.append(
                            (
                                title,
                                '<li><a href="%s%s%s">%s</a></li>'
                                % (
                                    req.prefix,
                                    urlquote(req.path),
                                    params
                                    and ("?" + iri_to_uri(params.urlencode()))
                                    or "",
                                    str(escape(capfirst(title))),
                                ),
                                req.path,
                            )
                        )
                    else:
                        if not req.GET or "noautofilter" in req.GET:
                            args = ""
                        else:
                            args = "?%s" % iri_to_uri(req.GET.urlencode())
                        cur.append(
                            (
                                title,
                                '<li><a href="%s%s%s">%s</a></li>'
                                % (
                                    req.prefix,
                                    urlquote(req.path),
                                    args,
                                    str(escape(capfirst(title))),
                                ),
                                req.path,
                            )
                        )
                    count += 1

                # Limit the number of crumbs.
                while count > MAX_CRUMBS:
                    count -= 1
                    del cur[0]
            except Exception:
                # Ignore errors to fail in a clean and graceful way
                pass

        # Update the current session
        req.session["crumbs"][req.prefix] = cur

        # Now create HTML code to return
        return "".join([i[1] for i in cur])
 def model_index_html(self, request, model, site):
     fields = self.field_dict(model)
     if not fields:
         return u''
     return mark_safe(u'<p class="filter"><strong>View by:</strong> %s</p>' % \
         u', '.join(['<a href="fields/%s/">%s</a>' % (f.name, force_unicode(capfirst(f.verbose_name))) for f in fields.values()]))
Пример #55
0
def start(http_request):
    """
    Front page with URL input, browser chooser, and options.
    """
    if (http_request.user.is_anonymous()
            and hasattr(settings, 'ALLOW_ANONYMOUS_REQUESTS')
            and not settings.ALLOW_ANONYMOUS_REQUESTS):
        url = '/'
        if http_request.META['QUERY_STRING']:
            url += '?' + http_request.META['QUERY_STRING']
        return error_page(
            http_request, _("login required"),
            _("Anonymous screenshot requests are not allowed."),
            u'<a href="/accounts/login/?next=%s">%s</a>' %
            (urllib.quote(url.encode('utf-8')),
             _("Please log in with your username and password.")))
    # Initialize forms.
    post = http_request.POST or None
    url_form = UrlForm(post)
    features_form = FeaturesForm(post)
    options_form = OptionsForm(post)
    special_form = SpecialForm(post)
    # Get available choices from database, with correct translations.
    active_factories = Factory.objects.filter(
        last_poll__gte=last_poll_timeout())
    active_browsers = Browser.objects.filter(factory__in=active_factories,
                                             active=True)
    if not active_browsers:
        return error_page(http_request, _("out of service"),
                          _("No active screenshot factories."),
                          _("Please try again later."))
    features_form.load_choices(active_browsers)
    options_form.load_choices(active_factories)
    # Validate posted data.
    valid_post = (url_form.is_valid() and options_form.is_valid()
                  and features_form.is_valid() and special_form.is_valid())
    # Preload some database entries for browser forms
    preload_foreign_keys(active_browsers,
                         factory=active_factories,
                         factory__operating_system=True,
                         browser_group=True,
                         engine=True)
    # Select browsers according to GET request
    selected_browsers = None
    if 'browsers' in http_request.GET:
        selected_browsers = http_request.GET['browsers'].split()
    # Browser forms for each platform.
    browser_forms = []
    for platform in Platform.objects.all():
        browser_form = BrowsersForm(active_browsers, platform, post,
                                    selected_browsers)
        browser_form.platform_name = \
            unicode(platform).lower().replace(' ', '-')
        if browser_form.is_bound:
            browser_form.full_clean()
        if browser_form.fields:
            browser_forms.append(browser_form)
        valid_post = valid_post and browser_form.is_valid()
    browser_forms[0].is_first = True
    browser_forms[-1].is_last = True
    priority = 0
    if valid_post:
        if (url_form.cleaned_data['shocksite_keywords'] >
                settings.SHOCKSITE_KEYWORDS_ALLOWED):
            # Ignore screenshot requests for shock sites.
            priority = -url_form.cleaned_data['shocksite_keywords']
        elif 'shotserver04.priority' in settings.INSTALLED_APPS:
            # Get priority processing for domain or user.
            from shotserver04.priority import domain_priority, user_priority
            priority = max(domain_priority(url_form.cleaned_data['domain']),
                           user_priority(http_request.user))
        usage_limited = check_usage_limits(http_request, priority,
                                           url_form.cleaned_data['website'],
                                           url_form.cleaned_data['domain'])
        if usage_limited:
            valid_post = False
    if not valid_post:
        # Show HTML form.
        if 'url' in http_request.GET:
            url_form.fields['url'].initial = http_request.GET['url']
        multi_column(browser_forms)
        selectors = mark_safe(',\n'.join([
            SELECTOR_TEMPLATE % (plus_minus, capfirst(text))
            for text, plus_minus in selector_pairs(browser_forms)
        ]))
        news_list = NewsItem.objects.all()[:10]
        sponsors_list = Sponsor.objects.filter(front_page=True)
        show_special_form = http_request.user.is_authenticated()
        return render_to_response(
            'start/start.html',
            locals(),
            context_instance=RequestContext(http_request))
    # Create screenshot requests and redirect to website overview.
    expire = datetime.now() + timedelta(minutes=30)
    values = {
        'website': url_form.cleaned_data['website'],
        'ip': http_request.META['REMOTE_ADDR'],
        'user': None,
    }
    if http_request.user.is_authenticated():
        values['user'] = http_request.user
    values.update(options_form.cleaned_data)
    values.update(features_form.cleaned_data)
    values.update(special_form.cleaned_data)
    match_values = {}
    for key in values:
        if values[key] is None:
            match_values[key + '__isnull'] = True
        else:
            match_values[key] = values[key]
    existing = RequestGroup.objects.filter(
        expire__gte=datetime.now(), **match_values).order_by('-submitted')
    if (len(existing) and
            existing[0].request_set.filter(screenshot__isnull=True).count()):
        # Previous request group is still pending, reuse it.
        request_group = existing[0]
        request_group.update_fields(expire=expire)
        if priority > request_group.priority:
            request_group.update_fields(priority=priority)
    else:
        request_group = RequestGroup.objects.create(expire=expire,
                                                    priority=priority,
                                                    **values)
    for browser_form in browser_forms:
        create_platform_requests(request_group, browser_form.platform,
                                 browser_form, priority)
    # Make sure that the redirect will show the new request group
    transaction.commit()
    # return render_to_response('debug.html', locals(),
    #     context_instance=RequestContext(http_request))
    return HttpResponseRedirect(values['website'].get_absolute_url())
Пример #56
0
    def index(self, request, extra_context=None):
        """
        Displays the main admin index page, which lists all of the installed
        apps that have been registered in this site.
        """
        app_dict = {}
        user = request.user
        for model, model_admin in self._registry.items():
            app_label = model._meta.app_label
            has_module_perms = user.has_module_perms(app_label)

            if has_module_perms:
                perms = model_admin.get_model_perms(request)

                # Check whether user has any perm for this module.
                # If so, add the module to the model_list.
                if True in perms.values():
                    info = (app_label, model._meta.model_name)
                    model_dict = {
                        'name': capfirst(model._meta.verbose_name_plural),
                        'object_name': model._meta.object_name,
                        'perms': perms,
                    }
                    if perms.get('change', False):
                        try:
                            model_dict['admin_url'] = reverse(
                                'admin:%s_%s_changelist' % info,
                                current_app=self.name)
                        except NoReverseMatch:
                            pass
                    if perms.get('add', False):
                        try:
                            model_dict['add_url'] = reverse(
                                'admin:%s_%s_add' % info,
                                current_app=self.name)
                        except NoReverseMatch:
                            pass
                    if app_label in app_dict:
                        app_dict[app_label]['models'].append(model_dict)
                    else:
                        app_dict[app_label] = {
                            'name':
                            apps.get_app_config(app_label).verbose_name,
                            'app_label':
                            app_label,
                            'app_url':
                            reverse('admin:app_list',
                                    kwargs={'app_label': app_label},
                                    current_app=self.name),
                            'has_module_perms':
                            has_module_perms,
                            'models': [model_dict],
                        }

        # Sort the apps alphabetically.
        app_list = list(six.itervalues(app_dict))
        app_list.sort(key=lambda x: x['name'].lower())

        # Sort the models alphabetically within each app.
        for app in app_list:
            app['models'].sort(key=lambda x: x['name'])

        context = dict(
            self.each_context(),
            title=self.index_title,
            app_list=app_list,
        )
        context.update(extra_context or {})
        return TemplateResponse(request,
                                self.index_template or 'admin/index.html',
                                context,
                                current_app=self.name)
Пример #57
0
class PreferencesForm(forms.Form):
    language = forms.ChoiceField(
        label=_("language"), initial="auto", choices=User.languageList
    )
    pagesize = forms.IntegerField(label=_("Page size"), required=False, initial=100)
    theme = forms.ChoiceField(
        label=_("Theme"),
        required=False,
        choices=[(i, capfirst(i)) for i in settings.THEMES],
    )
    cur_password = forms.CharField(
        # . Translators: Translation included with Django
        label=_("Change password"),
        required=False,
        # . Translators: Translation included with Django
        help_text=_("Old password"),
        widget=forms.PasswordInput(),
    )
    new_password1 = forms.CharField(
        label="",
        required=False,
        # . Translators: Translation included with Django
        help_text=password_validators_help_text_html(
            get_password_validators(settings.AUTH_PASSWORD_VALIDATORS)
        ),
        widget=forms.PasswordInput(),
    )
    new_password2 = forms.CharField(
        label="",
        required=False,
        # . Translators: Translation included with Django
        help_text=_("New password confirmation"),
        widget=forms.PasswordInput(),
    )

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        if len(settings.THEMES) == 1:
            # If there is only one theme make this choice unavailable
            self.fields.pop("theme")

    def clean(self):
        newdata = super().clean()
        if newdata.get("pagesize", 0) > 10000:
            raise forms.ValidationError("Maximum page size is 10000.")
        if newdata.get("pagesize", 25) < 25:
            raise forms.ValidationError("Minimum page size is 25.")
        if newdata["cur_password"]:
            if not self.user.check_password(newdata["cur_password"]):
                # fmt: off
                raise forms.ValidationError(
                    # . Translators: Translation included with Django
                    _("Your old password was entered incorrectly. Please enter it again.")
                )
                # fmt: on
            # Validate_password raises a ValidationError
            validate_password(
                newdata["new_password1"],
                self.user,
                get_password_validators(settings.AUTH_PASSWORD_VALIDATORS),
            )
            if newdata["new_password1"] != newdata["new_password2"]:
                # . Translators: Translation included with Django
                raise forms.ValidationError("The two password fields didn't match.")
Пример #58
0
 def get_success_message(self, instance):
     return _("{model_name} '{instance}' updated.").format(
         model_name=capfirst(self.verbose_name), instance=instance)
Пример #59
0
def get_app_list(request):
    """Django 1.8 way to get application registred at default Admin Site."""
    app_dict = {}
    user = request.user

    for model, model_admin in site._registry.items():
        app_label = model._meta.app_label
        has_module_perms = user.has_module_perms(app_label)

        if has_module_perms:
            perms = model_admin.get_model_perms(request)

            # Check whether user has any perm for this module.
            # If so, add the module to the model_list.
            if True in perms.values():
                info = (app_label, model._meta.model_name)
                model_icon = '<i class="material-icons admin-modelicon admin-modelicon-{}-{}"></i>'.format(
                    app_label, model._meta.model_name)
                if hasattr(model_admin, 'icon'):
                    model_icon = model_admin.icon
                model_dict = {
                    'name': capfirst(model._meta.verbose_name_plural),
                    'object_name': model._meta.object_name,
                    'perms': perms,
                    'icon': mark_safe(model_icon)
                }
                if perms.get('change', False):
                    try:
                        model_dict['admin_url'] = reverse(
                            'admin:%s_%s_changelist' % info,
                            current_app=site.name)
                        if request.path.startswith(model_dict['admin_url']):
                            model_dict['active'] = True
                    except NoReverseMatch:
                        pass
                if app_label in app_dict:
                    app_dict[app_label]['models'].append(model_dict)
                else:
                    app_config = apps.get_app_config(app_label)

                    app_name = app_config.verbose_name
                    if len(app_name) > 23:
                        app_name = app_label.title()
                    app_name = app_name.replace('_', ' ')

                    app_icon = '<i class="material-icons admin-appicon admin-appicon-{}"></i>'.format(
                        app_label)
                    if hasattr(app_config, 'icon'):
                        app_icon = app_config.icon

                    app_dict[app_label] = {
                        'name':
                        app_name,
                        'app_label':
                        app_label,
                        'app_icon':
                        mark_safe(app_icon),
                        'app_url':
                        reverse('admin:app_list',
                                kwargs={'app_label': app_label},
                                current_app=site.name),
                        'has_module_perms':
                        has_module_perms,
                        'models': [model_dict],
                    }

                    if request.path.startswith(app_dict[app_label]['app_url']):
                        app_dict[app_label]['active'] = True

    # Sort the apps alphabetically.
    app_list = list(six.itervalues(app_dict))
    app_list.sort(key=lambda x: x['name'].lower())

    # Sort the models alphabetically within each app.
    for app in app_list:
        app['models'].sort(key=lambda x: x['name'])

    return app_list
Пример #60
0
def get_field_kwargs(field_name, model_field):
    """
    Creating a default instance of a basic non-relational field.
    """
    kwargs = {}

    # The following will only be used by ModelField classes.
    # Gets removed for everything else.
    kwargs['model_field'] = model_field

    if hasattr(model_field, 'verbose_name') and needs_label(
            model_field, field_name):
        kwargs['label'] = capfirst(model_field.verbose_name)

    if hasattr(model_field, 'help_text'):
        kwargs['help_text'] = model_field.help_text

    if isinstance(model_field, me_fields.DecimalField):
        precision = model_field.precision
        max_value = getattr(model_field, 'max_value', None)
        if max_value is not None:
            max_length = len(str(max_value)) + precision
        else:
            max_length = 65536
        kwargs['decimal_places'] = precision
        kwargs['max_digits'] = max_length

    if isinstance(model_field, me_fields.GeoJsonBaseField):
        kwargs['geo_type'] = model_field._type

    if isinstance(
            model_field, me_fields.SequenceField
    ) or model_field.primary_key or model_field.db_field == '_id':
        # If this field is read-only, then return early.
        # Further keyword arguments are not valid.
        kwargs['read_only'] = True
        return kwargs

    if model_field.default and not isinstance(model_field,
                                              me_fields.ComplexBaseField):
        kwargs['default'] = model_field.default

    if model_field.null:
        kwargs['allow_null'] = True

    if model_field.null and isinstance(model_field, me_fields.StringField):
        kwargs['allow_blank'] = True

    if 'default' not in kwargs:
        kwargs['required'] = model_field.required

        # handle special cases - compound fields: mongoengine.ListField/DictField
        if kwargs['required'] is True:
            if isinstance(model_field, me_fields.ListField) or isinstance(
                    model_field, me_fields.DictField):
                kwargs['allow_empty'] = False

    if model_field.choices:
        # If this model field contains choices, then return early.
        # Further keyword arguments are not valid.
        kwargs['choices'] = model_field.choices
        return kwargs

    if isinstance(model_field, me_fields.StringField):
        if model_field.regex:
            kwargs['regex'] = model_field.regex

    max_length = getattr(model_field, 'max_length', None)
    if max_length is not None and isinstance(model_field,
                                             me_fields.StringField):
        kwargs['max_length'] = max_length

    min_length = getattr(model_field, 'min_length', None)
    if min_length is not None and isinstance(model_field,
                                             me_fields.StringField):
        kwargs['min_length'] = min_length

    max_value = getattr(model_field, 'max_value', None)
    if max_value is not None and isinstance(model_field, NUMERIC_FIELD_TYPES):
        kwargs['max_value'] = max_value

    min_value = getattr(model_field, 'min_value', None)
    if min_value is not None and isinstance(model_field, NUMERIC_FIELD_TYPES):
        kwargs['min_value'] = min_value

    return kwargs