コード例 #1
0
ファイル: views.py プロジェクト: Matthijs990/os-sys-github
def serve(request, path, insecure=False, **kwargs):
    """
    Serve static files below a given point in the directory structure or
    from locations inferred from the staticfiles finders.

    To use, put a URL pattern such as::

        from server.contrib.staticfiles import views

        url(r'^(?P<path>.*)$', views.serve)

    in your URLconf.

    It uses the server.views.static.serve() view to serve the found files.
    """
    if not settings.DEBUG and not insecure:
        raise Http404
    normalized_path = posixpath.normpath(path).lstrip('/')
    absolute_path = finders.find(normalized_path)
    if not absolute_path:
        if path.endswith('/') or path == '':
            raise Http404("Directory indexes are not allowed here.")
        raise Http404("'%s' could not be found" % path)
    document_root, path = os.path.split(absolute_path)
    return static.serve(request, path, document_root=document_root, **kwargs)
コード例 #2
0
ファイル: views.py プロジェクト: Matthijs990/os-sys-github
def kml(request,
        label,
        model,
        field_name=None,
        compress=False,
        using=DEFAULT_DB_ALIAS):
    """
    This view generates KML for the given app label, model, and field name.

    The field name must be that of a geographic field.
    """
    placemarks = []
    try:
        klass = apps.get_model(label, model)
    except LookupError:
        raise Http404(
            'You must supply a valid app label and module name.  Got "%s.%s"' %
            (label, model))

    if field_name:
        try:
            field = klass._meta.get_field(field_name)
            if not isinstance(field, GeometryField):
                raise FieldDoesNotExist
        except FieldDoesNotExist:
            raise Http404('Invalid geometry field.')

    connection = connections[using]

    if connection.features.has_AsKML_function:
        # Database will take care of transformation.
        placemarks = klass._default_manager.using(using).annotate(
            kml=AsKML(field_name))
    else:
        # If the database offers no KML method, we use the `kml`
        # attribute of the lazy geometry instead.
        placemarks = []
        if connection.features.has_Transform_function:
            qs = klass._default_manager.using(using).annotate(
                **{'%s_4326' % field_name: Transform(field_name, 4326)})
            field_name += '_4326'
        else:
            qs = klass._default_manager.using(using).all()
        for mod in qs:
            mod.kml = getattr(mod, field_name).kml
            placemarks.append(mod)

    # Getting the render function and rendering to the correct.
    if compress:
        render = render_to_kmz
    else:
        render = render_to_kml
    return render('gis/kml/placemarks.kml', {'places': placemarks})
コード例 #3
0
def sitemap(request,
            sitemaps,
            section=None,
            template_name='sitemap.xml',
            content_type='application/xml'):

    req_protocol = request.scheme
    req_site = get_current_site(request)

    if section is not None:
        if section not in sitemaps:
            raise Http404("No sitemap available for section: %r" % section)
        maps = [sitemaps[section]]
    else:
        maps = sitemaps.values()
    page = request.GET.get("p", 1)

    lastmod = None
    all_sites_lastmod = True
    urls = []
    for site in maps:
        try:
            if callable(site):
                site = site()
            urls.extend(
                site.get_urls(page=page, site=req_site, protocol=req_protocol))
            if all_sites_lastmod:
                site_lastmod = getattr(site, 'latest_lastmod', None)
                if site_lastmod is not None:
                    site_lastmod = (site_lastmod.utctimetuple() if isinstance(
                        site_lastmod, datetime.datetime) else
                                    site_lastmod.timetuple())
                    lastmod = site_lastmod if lastmod is None else max(
                        lastmod, site_lastmod)
                else:
                    all_sites_lastmod = False
        except EmptyPage:
            raise Http404("Page %s empty" % page)
        except PageNotAnInteger:
            raise Http404("No page '%s'" % page)
    response = TemplateResponse(request,
                                template_name, {'urlset': urls},
                                content_type=content_type)
    if all_sites_lastmod and lastmod is not None:
        # if lastmod is defined for all sites, set header so as
        # ConditionalGetMiddleware is able to send 304 NOT MODIFIED
        response['Last-Modified'] = http_date(timegm(lastmod))
    return response
コード例 #4
0
ファイル: dates.py プロジェクト: Matthijs990/os-sys-github
    def get_dated_queryset(self, **lookup):
        """
        Get a queryset properly filtered according to `allow_future` and any
        extra lookup kwargs.
        """
        qs = self.get_queryset().filter(**lookup)
        date_field = self.get_date_field()
        allow_future = self.get_allow_future()
        allow_empty = self.get_allow_empty()
        paginate_by = self.get_paginate_by(qs)

        if not allow_future:
            now = timezone.now(
            ) if self.uses_datetime_field else timezone_today()
            qs = qs.filter(**{'%s__lte' % date_field: now})

        if not allow_empty:
            # When pagination is enabled, it's better to do a cheap query
            # than to load the unpaginated queryset in memory.
            is_empty = not qs if paginate_by is None else not qs.exists()
            if is_empty:
                raise Http404(
                    _("No %(verbose_name_plural)s available") % {
                        'verbose_name_plural':
                        qs.model._meta.verbose_name_plural,
                    })

        return qs
コード例 #5
0
ファイル: admin.py プロジェクト: Matthijs990/os-sys-github
 def _add_view(self, request, form_url='', extra_context=None):
     # It's an error for a user to have add permission but NOT change
     # permission for users. If we allowed such users to add users, they
     # could create superusers, which would mean they would essentially have
     # the permission to change users. To avoid the problem entirely, we
     # disallow users from adding users if they don't have change
     # permission.
     if not self.has_change_permission(request):
         if self.has_add_permission(request) and settings.DEBUG:
             # Raise Http404 in debug mode so that the user gets a helpful
             # error message.
             raise Http404(
                 'Your user does not have the "Change user" permission. In '
                 'order to add users, Server requires that your user '
                 'account have both the "Add user" and "Change user" '
                 'permissions set.')
         raise PermissionDenied
     if extra_context is None:
         extra_context = {}
     username_field = self.model._meta.get_field(self.model.USERNAME_FIELD)
     defaults = {
         'auto_populated_fields': (),
         'username_help_text': username_field.help_text,
     }
     extra_context.update(defaults)
     return super().add_view(request, form_url, extra_context)
コード例 #6
0
    def get(self, request, *args, **kwargs):
        """
        Return a JsonResponse with search results of the form:
        {
            results: [{id: "123" text: "foo"}],
            pagination: {more: true}
        }
        """
        if not self.model_admin.get_search_fields(request):
            raise Http404(
                '%s must have search_fields for the autocomplete_view.' %
                type(self.model_admin).__name__)
        if not self.has_perm(request):
            return JsonResponse({'error': '403 Forbidden'}, status=403)

        self.term = request.GET.get('term', '')
        self.paginator_class = self.model_admin.paginator
        self.object_list = self.get_queryset()
        context = self.get_context_data()
        return JsonResponse({
            'results': [{
                'id': str(obj.pk),
                'text': str(obj)
            } for obj in context['object_list']],
            'pagination': {
                'more': context['page_obj'].has_next()
            },
        })
コード例 #7
0
ファイル: dates.py プロジェクト: Matthijs990/os-sys-github
    def get_object(self, queryset=None):
        """Get the object this request displays."""
        year = self.get_year()
        month = self.get_month()
        day = self.get_day()
        date = _date_from_string(year, self.get_year_format(), month,
                                 self.get_month_format(), day,
                                 self.get_day_format())

        # Use a custom queryset if provided
        qs = self.get_queryset() if queryset is None else queryset

        if not self.get_allow_future() and date > datetime.date.today():
            raise Http404(
                _("Future %(verbose_name_plural)s not available because "
                  "%(class_name)s.allow_future is False.") %
                {
                    'verbose_name_plural': qs.model._meta.verbose_name_plural,
                    'class_name': self.__class__.__name__,
                })

        # Filter down a queryset from self.queryset using the date from the
        # URL. This'll get passed as the queryset to DetailView.get_object,
        # which'll handle the 404
        lookup_kwargs = self._make_single_date_lookup(date)
        qs = qs.filter(**lookup_kwargs)

        return super().get_object(queryset=qs)
コード例 #8
0
def feed(request, url, feed_dict=None):
    """Provided for backwards compatibility."""
    if not feed_dict:
        raise Http404(_("No feeds are registered."))

    slug = url.partition('/')[0]
    try:
        f = feed_dict[slug]
    except KeyError:
        raise Http404(_("Slug %r isn't registered.") % slug)

    instance = f()
    instance.feed_url = getattr(f, 'feed_url', None) or request.path
    instance.title_template = f.title_template or ('feeds/%s_title.html' %
                                                   slug)
    instance.description_template = f.description_template or (
        'feeds/%s_description.html' % slug)
    return instance(request)
コード例 #9
0
ファイル: dates.py プロジェクト: Matthijs990/os-sys-github
    def _get_next_year(self, date):
        """
        Return the start date of the next interval.

        The interval is defined by start date <= item date < next start date.
        """
        try:
            return date.replace(year=date.year + 1, month=1, day=1)
        except ValueError:
            raise Http404(_("Date out of range"))
コード例 #10
0
ファイル: dates.py プロジェクト: Matthijs990/os-sys-github
    def _get_next_week(self, date):
        """
        Return the start date of the next interval.

        The interval is defined by start date <= item date < next start date.
        """
        try:
            return date + datetime.timedelta(days=7 - self._get_weekday(date))
        except OverflowError:
            raise Http404(_("Date out of range"))
コード例 #11
0
ファイル: dates.py プロジェクト: Matthijs990/os-sys-github
 def get_month(self):
     """Return the month for which this view should display data."""
     month = self.month
     if month is None:
         try:
             month = self.kwargs['month']
         except KeyError:
             try:
                 month = self.request.GET['month']
             except KeyError:
                 raise Http404(_("No month specified"))
     return month
コード例 #12
0
ファイル: dates.py プロジェクト: Matthijs990/os-sys-github
 def get_week(self):
     """Return the week for which this view should display data."""
     week = self.week
     if week is None:
         try:
             week = self.kwargs['week']
         except KeyError:
             try:
                 week = self.request.GET['week']
             except KeyError:
                 raise Http404(_("No week specified"))
     return week
コード例 #13
0
ファイル: dates.py プロジェクト: Matthijs990/os-sys-github
 def get_year(self):
     """Return the year for which this view should display data."""
     year = self.year
     if year is None:
         try:
             year = self.kwargs['year']
         except KeyError:
             try:
                 year = self.request.GET['year']
             except KeyError:
                 raise Http404(_("No year specified"))
     return year
コード例 #14
0
ファイル: dates.py プロジェクト: Matthijs990/os-sys-github
 def get_day(self):
     """Return the day for which this view should display data."""
     day = self.day
     if day is None:
         try:
             day = self.kwargs['day']
         except KeyError:
             try:
                 day = self.request.GET['day']
             except KeyError:
                 raise Http404(_("No day specified"))
     return day
コード例 #15
0
ファイル: list.py プロジェクト: Matthijs990/os-sys-github
 def paginate_queryset(self, queryset, page_size):
     """Paginate the queryset, if needed."""
     paginator = self.get_paginator(
         queryset, page_size, orphans=self.get_paginate_orphans(),
         allow_empty_first_page=self.get_allow_empty())
     page_kwarg = self.page_kwarg
     page = self.kwargs.get(page_kwarg) or self.request.GET.get(page_kwarg) or 1
     try:
         page_number = int(page)
     except ValueError:
         if page == 'last':
             page_number = paginator.num_pages
         else:
             raise Http404(_("Page is not 'last', nor can it be converted to an int."))
     try:
         page = paginator.page(page_number)
         return (paginator, page, page.object_list, page.has_other_pages())
     except InvalidPage as e:
         raise Http404(_('Invalid page (%(page_number)s): %(message)s') % {
             'page_number': page_number,
             'message': str(e)
         })
コード例 #16
0
ファイル: views.py プロジェクト: Matthijs990/os-sys-github
 def __call__(self, request, *args, **kwargs):
     try:
         obj = self.get_object(request, *args, **kwargs)
     except ObjectDoesNotExist:
         raise Http404('Feed object does not exist.')
     feedgen = self.get_feed(obj, request)
     response = HttpResponse(content_type=feedgen.content_type)
     if hasattr(self, 'item_pubdate') or hasattr(self, 'item_updateddate'):
         # if item_pubdate or item_updateddate is defined for the feed, set
         # header so as ConditionalGetMiddleware is able to send 304 NOT MODIFIED
         response['Last-Modified'] = http_date(
             timegm(feedgen.latest_post_date().utctimetuple()))
     feedgen.write(response, 'utf-8')
     return response
コード例 #17
0
def serve(request, path, document_root=None, show_indexes=False):
    """
    Serve static files below a given point in the directory structure.

    To use, put a URL pattern such as::

        from server.views.static import serve

        url(r'^(?P<path>.*)$', serve, {'document_root': '/path/to/my/files/'})

    in your URLconf. You must provide the ``document_root`` param. You may
    also set ``show_indexes`` to ``True`` if you'd like to serve a basic index
    of the directory.  This index view will use the template hardcoded below,
    but if you'd like to override it, you can create a template called
    ``static/directory_index.html``.
    """
    path = posixpath.normpath(path).lstrip('/')
    fullpath = Path(safe_join(document_root, path))
    if fullpath.is_dir():
        if show_indexes:
            return directory_index(path, fullpath)
        raise Http404(_("Directory indexes are not allowed here."))
    if not fullpath.exists():
        raise Http404(_('"%(path)s" does not exist') % {'path': fullpath})
    # Respect the If-Modified-Since header.
    statobj = fullpath.stat()
    if not was_modified_since(request.META.get('HTTP_IF_MODIFIED_SINCE'),
                              statobj.st_mtime, statobj.st_size):
        return HttpResponseNotModified()
    content_type, encoding = mimetypes.guess_type(str(fullpath))
    content_type = content_type or 'application/octet-stream'
    response = FileResponse(fullpath.open('rb'), content_type=content_type)
    response["Last-Modified"] = http_date(statobj.st_mtime)
    if encoding:
        response["Content-Encoding"] = encoding
    return response
コード例 #18
0
ファイル: list.py プロジェクト: Matthijs990/os-sys-github
    def get(self, request, *args, **kwargs):
        self.object_list = self.get_queryset()
        allow_empty = self.get_allow_empty()

        if not allow_empty:
            # When pagination is enabled and object_list is a queryset,
            # it's better to do a cheap query than to load the unpaginated
            # queryset in memory.
            if self.get_paginate_by(self.object_list) is not None and hasattr(self.object_list, 'exists'):
                is_empty = not self.object_list.exists()
            else:
                is_empty = not self.object_list
            if is_empty:
                raise Http404(_("Empty list and '%(class_name)s.allow_empty' is False.") % {
                    'class_name': self.__class__.__name__,
                })
        context = self.get_context_data()
        return self.render_to_response(context)
コード例 #19
0
def get_list_or_404(klass, *args, **kwargs):
    """
    Use filter() to return a list of objects, or raise a Http404 exception if
    the list is empty.

    klass may be a Model, Manager, or QuerySet object. All other passed
    arguments and keyword arguments are used in the filter() query.
    """
    queryset = _get_queryset(klass)
    if not hasattr(queryset, 'filter'):
        klass__name = klass.__name__ if isinstance(klass, type) else klass.__class__.__name__
        raise ValueError(
            "First argument to get_list_or_404() must be a Model, Manager, or "
            "QuerySet, not '%s'." % klass__name
        )
    obj_list = list(queryset.filter(*args, **kwargs))
    if not obj_list:
        raise Http404('No %s matches the given query.' % queryset.model._meta.object_name)
    return obj_list
コード例 #20
0
ファイル: dates.py プロジェクト: Matthijs990/os-sys-github
    def get_date_list(self, queryset, date_type=None, ordering='ASC'):
        """
        Get a date list by calling `queryset.dates/datetimes()`, checking
        along the way for empty lists that aren't allowed.
        """
        date_field = self.get_date_field()
        allow_empty = self.get_allow_empty()
        if date_type is None:
            date_type = self.get_date_list_period()

        if self.uses_datetime_field:
            date_list = queryset.datetimes(date_field, date_type, ordering)
        else:
            date_list = queryset.dates(date_field, date_type, ordering)
        if date_list is not None and not date_list and not allow_empty:
            raise Http404(
                _("No %(verbose_name_plural)s available") % {
                    'verbose_name_plural':
                    queryset.model._meta.verbose_name_plural,
                })

        return date_list
コード例 #21
0
ファイル: dates.py プロジェクト: Matthijs990/os-sys-github
def _date_from_string(year,
                      year_format,
                      month='',
                      month_format='',
                      day='',
                      day_format='',
                      delim='__'):
    """
    Get a datetime.date object given a format string and a year, month, and day
    (only year is mandatory). Raise a 404 for an invalid date.
    """
    format = year_format + delim + month_format + delim + day_format
    datestr = str(year) + delim + str(month) + delim + str(day)
    try:
        return datetime.datetime.strptime(datestr, format).date()
    except ValueError:
        raise Http404(
            _("Invalid date string '%(datestr)s' given format '%(format)s'") %
            {
                'datestr': datestr,
                'format': format,
            })
コード例 #22
0
def get_object_or_404(klass, *args, **kwargs):
    """
    Use get() to return an object, or raise a Http404 exception if the object
    does not exist.

    klass may be a Model, Manager, or QuerySet object. All other passed
    arguments and keyword arguments are used in the get() query.

    Like with QuerySet.get(), MultipleObjectsReturned is raised if more than
    one object is found.
    """
    queryset = _get_queryset(klass)
    if not hasattr(queryset, 'get'):
        klass__name = klass.__name__ if isinstance(klass, type) else klass.__class__.__name__
        raise ValueError(
            "First argument to get_object_or_404() must be a Model, Manager, "
            "or QuerySet, not '%s'." % klass__name
        )
    try:
        return queryset.get(*args, **kwargs)
    except queryset.model.DoesNotExist:
        raise Http404('No %s matches the given query.' % queryset.model._meta.object_name)
コード例 #23
0
ファイル: detail.py プロジェクト: Matthijs990/os-sys-github
    def get_object(self, queryset=None):
        """
        Return the object the view is displaying.

        Require `self.queryset` and a `pk` or `slug` argument in the URLconf.
        Subclasses can override this to return any object.
        """
        # Use a custom queryset if provided; this is required for subclasses
        # like DateDetailView
        if queryset is None:
            queryset = self.get_queryset()

        # Next, try looking up by primary key.
        pk = self.kwargs.get(self.pk_url_kwarg)
        slug = self.kwargs.get(self.slug_url_kwarg)
        if pk is not None:
            queryset = queryset.filter(pk=pk)

        # Next, try looking up by slug.
        if slug is not None and (pk is None or self.query_pk_and_slug):
            slug_field = self.get_slug_field()
            queryset = queryset.filter(**{slug_field: slug})

        # If none of those are defined, it's an error.
        if pk is None and slug is None:
            raise AttributeError(
                "Generic detail view %s must be called with either an object "
                "pk or a slug in the URLconf." % self.__class__.__name__)

        try:
            # Get the single item from the filtered queryset
            obj = queryset.get()
        except queryset.model.DoesNotExist:
            raise Http404(
                _("No %(verbose_name)s found matching the query") %
                {'verbose_name': queryset.model._meta.verbose_name})
        return obj
コード例 #24
0
ファイル: views.py プロジェクト: Matthijs990/os-sys-github
def shortcut(request, content_type_id, object_id):
    """
    Redirect to an object's page based on a content-type ID and an object ID.
    """
    # Look up the object, making sure it's got a get_absolute_url() function.
    try:
        content_type = ContentType.objects.get(pk=content_type_id)
        if not content_type.model_class():
            raise Http404(
                _("Content type %(ct_id)s object has no associated model") %
                {'ct_id': content_type_id})
        obj = content_type.get_object_for_this_type(pk=object_id)
    except (ObjectDoesNotExist, ValueError):
        raise Http404(
            _("Content type %(ct_id)s object %(obj_id)s doesn't exist") % {
                'ct_id': content_type_id,
                'obj_id': object_id
            })

    try:
        get_absolute_url = obj.get_absolute_url
    except AttributeError:
        raise Http404(
            _("%(ct_name)s objects don't have a get_absolute_url() method") %
            {'ct_name': content_type.name})
    absurl = get_absolute_url()

    # Try to figure out the object's domain, so we can do a cross-site redirect
    # if necessary.

    # If the object actually defines a domain, we're done.
    if absurl.startswith(('http://', 'https://', '//')):
        return HttpResponseRedirect(absurl)

    # Otherwise, we need to introspect the object's relationships for a
    # relation to the Site object
    object_domain = None

    if apps.is_installed('server.contrib.sites'):
        Site = apps.get_model('sites.Site')

        opts = obj._meta

        # First, look for a many-to-many relationship to Site.
        for field in opts.many_to_many:
            if field.remote_field.model is Site:
                try:
                    # Caveat: In the case of multiple related Sites, this just
                    # selects the *first* one, which is arbitrary.
                    object_domain = getattr(obj, field.name).all()[0].domain
                except IndexError:
                    pass
                if object_domain is not None:
                    break

        # Next, look for a many-to-one relationship to Site.
        if object_domain is None:
            for field in obj._meta.fields:
                if field.remote_field and field.remote_field.model is Site:
                    try:
                        site = getattr(obj, field.name)
                    except Site.DoesNotExist:
                        continue
                    if site is not None:
                        object_domain = site.domain
                    if object_domain is not None:
                        break

        # Fall back to the current site (if possible).
        if object_domain is None:
            try:
                object_domain = Site.objects.get_current(request).domain
            except Site.DoesNotExist:
                pass

    else:
        # Fall back to the current request's site.
        object_domain = RequestSite(request).domain

    # If all that malarkey found an object domain, use it. Otherwise, fall back
    # to whatever get_absolute_url() returned.
    if object_domain is not None:
        protocol = request.scheme
        return HttpResponseRedirect('%s://%s%s' %
                                    (protocol, object_domain, absurl))
    else:
        return HttpResponseRedirect(absurl)
コード例 #25
0
    def get_context_data(self, **kwargs):
        model_name = self.kwargs['model_name']
        # Get the model class.
        try:
            app_config = apps.get_app_config(self.kwargs['app_label'])
        except LookupError:
            raise Http404(_("App %(app_label)r not found") % self.kwargs)
        try:
            model = app_config.get_model(model_name)
        except LookupError:
            raise Http404(
                _("Model %(model_name)r not found in app %(app_label)r") %
                self.kwargs)

        opts = model._meta

        title, body, metadata = utils.parse_docstring(model.__doc__)
        title = title and utils.parse_rst(title, 'model',
                                          _('model:') + model_name)
        body = body and utils.parse_rst(body, 'model',
                                        _('model:') + model_name)

        # Gather fields/field descriptions.
        fields = []
        for field in opts.fields:
            # ForeignKey is a special case since the field will actually be a
            # descriptor that returns the other object
            if isinstance(field, models.ForeignKey):
                data_type = field.remote_field.model.__name__
                app_label = field.remote_field.model._meta.app_label
                verbose = utils.parse_rst(
                    (_("the related `%(app_label)s.%(data_type)s` object") % {
                        'app_label': app_label,
                        'data_type': data_type,
                    }),
                    'model',
                    _('model:') + data_type,
                )
            else:
                data_type = get_readable_field_data_type(field)
                verbose = field.verbose_name
            fields.append({
                'name': field.name,
                'data_type': data_type,
                'verbose': verbose or '',
                'help_text': field.help_text,
            })

        # Gather many-to-many fields.
        for field in opts.many_to_many:
            data_type = field.remote_field.model.__name__
            app_label = field.remote_field.model._meta.app_label
            verbose = _("related `%(app_label)s.%(object_name)s` objects") % {
                'app_label': app_label,
                'object_name': data_type,
            }
            fields.append({
                'name':
                "%s.all" % field.name,
                "data_type":
                'List',
                'verbose':
                utils.parse_rst(
                    _("all %s") % verbose, 'model',
                    _('model:') + opts.model_name),
            })
            fields.append({
                'name':
                "%s.count" % field.name,
                'data_type':
                'Integer',
                'verbose':
                utils.parse_rst(
                    _("number of %s") % verbose, 'model',
                    _('model:') + opts.model_name),
            })

        methods = []
        # Gather model methods.
        for func_name, func in model.__dict__.items():
            if inspect.isfunction(func):
                try:
                    for exclude in MODEL_METHODS_EXCLUDE:
                        if func_name.startswith(exclude):
                            raise StopIteration
                except StopIteration:
                    continue
                verbose = func.__doc__
                verbose = verbose and (utils.parse_rst(
                    utils.trim_docstring(verbose), 'model',
                    _('model:') + opts.model_name))
                # If a method has no arguments, show it as a 'field', otherwise
                # as a 'method with arguments'.
                if func_has_no_args(func) and not func_accepts_kwargs(
                        func) and not func_accepts_var_args(func):
                    fields.append({
                        'name': func_name,
                        'data_type': get_return_data_type(func_name),
                        'verbose': verbose or '',
                    })
                else:
                    arguments = get_func_full_args(func)
                    # Join arguments with ', ' and in case of default value,
                    # join it with '='. Use repr() so that strings will be
                    # correctly displayed.
                    print_arguments = ', '.join([
                        '='.join(
                            list(arg_el[:1]) + [repr(el) for el in arg_el[1:]])
                        for arg_el in arguments
                    ])
                    methods.append({
                        'name': func_name,
                        'arguments': print_arguments,
                        'verbose': verbose or '',
                    })

        # Gather related objects
        for rel in opts.related_objects:
            verbose = _("related `%(app_label)s.%(object_name)s` objects") % {
                'app_label': rel.related_model._meta.app_label,
                'object_name': rel.related_model._meta.object_name,
            }
            accessor = rel.get_accessor_name()
            fields.append({
                'name':
                "%s.all" % accessor,
                'data_type':
                'List',
                'verbose':
                utils.parse_rst(
                    _("all %s") % verbose, 'model',
                    _('model:') + opts.model_name),
            })
            fields.append({
                'name':
                "%s.count" % accessor,
                'data_type':
                'Integer',
                'verbose':
                utils.parse_rst(
                    _("number of %s") % verbose, 'model',
                    _('model:') + opts.model_name),
            })
        return super().get_context_data(
            **{
                **kwargs,
                'name': '%s.%s' % (opts.app_label, opts.object_name),
                'summary': title,
                'description': body,
                'fields': fields,
                'methods': methods,
            })
コード例 #26
0
ファイル: admin.py プロジェクト: Matthijs990/os-sys-github
    def user_change_password(self, request, id, form_url=''):
        if not self.has_change_permission(request):
            raise PermissionDenied
        user = self.get_object(request, unquote(id))
        if user is None:
            raise Http404(
                _('%(name)s object with primary key %(key)r does not exist.') %
                {
                    'name': self.model._meta.verbose_name,
                    'key': escape(id),
                })
        if request.method == 'POST':
            form = self.change_password_form(user, request.POST)
            if form.is_valid():
                form.save()
                change_message = self.construct_change_message(
                    request, form, None)
                self.log_change(request, user, change_message)
                msg = gettext('Password changed successfully.')
                messages.success(request, msg)
                update_session_auth_hash(request, form.user)
                return HttpResponseRedirect(
                    reverse(
                        '%s:%s_%s_change' % (
                            self.admin_site.name,
                            user._meta.app_label,
                            user._meta.model_name,
                        ),
                        args=(user.pk, ),
                    ))
        else:
            form = self.change_password_form(user)

        fieldsets = [(None, {'fields': list(form.base_fields)})]
        adminForm = admin.helpers.AdminForm(form, fieldsets, {})

        context = {
            'title':
            _('Change password: %s') % escape(user.get_username()),
            'adminForm':
            adminForm,
            'form_url':
            form_url,
            'form':
            form,
            'is_popup': (IS_POPUP_VAR in request.POST
                         or IS_POPUP_VAR in request.GET),
            'add':
            True,
            'change':
            False,
            'has_delete_permission':
            False,
            'has_change_permission':
            True,
            'has_absolute_url':
            False,
            'opts':
            self.model._meta,
            'original':
            user,
            'save_as':
            False,
            'show_save':
            True,
            **self.admin_site.each_context(request),
        }

        request.current_app = self.admin_site.name

        return TemplateResponse(
            request,
            self.change_user_password_template
            or 'admin/auth/user/change_password.html',
            context,
        )