Esempio n. 1
0
def template_filter_index(request):
    if not utils.docutils_is_available:
        return missing_docutils_page(request)

    load_all_installed_template_libraries()

    filters = []
    app_libs = list(six.iteritems(template.libraries))
    builtin_libs = [(None, lib) for lib in template.builtins]
    for module_name, library in builtin_libs + app_libs:
        for filter_name, filter_func in library.filters.items():
            title, body, metadata = utils.parse_docstring(filter_func.__doc__)
            if title:
                title = utils.parse_rst(title, 'filter', _('filter:') + filter_name)
            if body:
                body = utils.parse_rst(body, 'filter', _('filter:') + filter_name)
            for key in metadata:
                metadata[key] = utils.parse_rst(metadata[key], 'filter', _('filter:') + filter_name)
            if library in template.builtins:
                tag_library = None
            else:
                tag_library = module_name.split('.')[-1]
            filters.append({
                'name': filter_name,
                'title': title,
                'body': body,
                'meta': metadata,
                'library': tag_library,
            })
    return render_to_response('admin_doc/template_filter_index.html', {
        'root_path': urlresolvers.reverse('admin:index'),
        'filters': filters
    }, context_instance=RequestContext(request))
Esempio n. 2
0
def sitemap(request, sitemaps, section=None):
    """
    This view generates a sitemap with additional geographic
    elements defined by Google.
    """
    maps, urls = [], []
    if section is not None:
        if section not in sitemaps:
            raise Http404(_("No sitemap available for section: %r") % section)
        maps.append(sitemaps[section])
    else:
        maps = list(six.itervalues(sitemaps))

    page = request.GET.get("p", 1)
    current_site = get_current_site(request)
    for site in maps:
        try:
            if callable(site):
                urls.extend(site().get_urls(page=page, site=current_site))
            else:
                urls.extend(site.get_urls(page=page, site=current_site))
        except EmptyPage:
            raise Http404(_("Page %s empty") % page)
        except PageNotAnInteger:
            raise Http404(_("No page '%s'") % page)
    xml = loader.render_to_string('gis/sitemaps/geo_sitemap.xml', {'urlset': urls})
    return HttpResponse(xml, content_type='application/xml')
Esempio n. 3
0
 def safe_summary(self, encoded):
     algorithm, salt, data = encoded.split('$', 2)
     assert algorithm == self.algorithm
     return SortedDict([
         (_('algorithm'), algorithm),
         (_('salt'), salt),
         (_('hash'), mask_hash(data, show=3)),
     ])
Esempio n. 4
0
 def safe_summary(self, encoded):
     algorithm, iterations, salt, hash = encoded.split('$', 3)
     assert algorithm == self.algorithm
     return SortedDict([
         (_('algorithm'), algorithm),
         (_('iterations'), iterations),
         (_('salt'), mask_hash(salt)),
         (_('hash'), mask_hash(hash)),
     ])
Esempio n. 5
0
    def __str__(self):
        if self.action_flag == ADDITION:
            return _('Added "%(object)s".') % {'object': self.object_repr}
        elif self.action_flag == CHANGE:
            return _('Changed "%(object)s" - %(changes)s') % {'object': self.object_repr, 'changes': self.change_message}
        elif self.action_flag == DELETION:
            return _('Deleted "%(object)s."') % {'object': self.object_repr}

        return _('LogEntry Object')
Esempio n. 6
0
 def add_fields(self, form, index):
     """A hook for adding extra fields on to each form instance."""
     if self.can_order:
         # Only pre-fill the ordering field for initial forms.
         if index is not None and index < self.initial_form_count():
             form.fields[ORDERING_FIELD_NAME] = IntegerField(label=_('Order'), initial=index+1, required=False)
         else:
             form.fields[ORDERING_FIELD_NAME] = IntegerField(label=_('Order'), required=False)
     if self.can_delete:
         form.fields[DELETION_FIELD_NAME] = BooleanField(label=_('Delete'), required=False)
Esempio n. 7
0
 def safe_summary(self, encoded):
     algorithm, empty, algostr, work_factor, data = encoded.split('$', 4)
     assert algorithm == self.algorithm
     salt, checksum = data[:22], data[22:]
     return SortedDict([
         (_('algorithm'), algorithm),
         (_('work factor'), work_factor),
         (_('salt'), mask_hash(salt)),
         (_('checksum'), mask_hash(checksum)),
     ])
Esempio n. 8
0
 def test_custom_fields(self):
     self.assertEqual(
         views.get_readable_field_data_type(fields.CustomField()),
         _('A custom field type')
     )
     self.assertEqual(
         views.get_readable_field_data_type(fields.DescriptionLackingField()),
         _('Field of type: %(field_type)s') % {
             'field_type': 'DescriptionLackingField'
         }
     )
Esempio n. 9
0
def naturaltime(value):
    """
    For date and time values shows how many seconds, minutes or hours ago
    compared to current timestamp returns representing string.
    """
    if not isinstance(value, date): # datetime is a subclass of date
        return value

    now = datetime.now(utc if is_aware(value) else None)
    if value < now:
        delta = now - value
        if delta.days != 0:
            return pgettext(
                'naturaltime', '%(delta)s ago'
            ) % {'delta': defaultfilters.timesince(value, now)}
        elif delta.seconds == 0:
            return _('now')
        elif delta.seconds < 60:
            return ungettext(
                'a second ago', '%(count)s seconds ago', delta.seconds
            ) % {'count': delta.seconds}
        elif delta.seconds // 60 < 60:
            count = delta.seconds // 60
            return ungettext(
                'a minute ago', '%(count)s minutes ago', count
            ) % {'count': count}
        else:
            count = delta.seconds // 60 // 60
            return ungettext(
                'an hour ago', '%(count)s hours ago', count
            ) % {'count': count}
    else:
        delta = value - now
        if delta.days != 0:
            return pgettext(
                'naturaltime', '%(delta)s from now'
            ) % {'delta': defaultfilters.timeuntil(value, now)}
        elif delta.seconds == 0:
            return _('now')
        elif delta.seconds < 60:
            return ungettext(
                'a second from now', '%(count)s seconds from now', delta.seconds
            ) % {'count': delta.seconds}
        elif delta.seconds // 60 < 60:
            count = delta.seconds // 60
            return ungettext(
                'a minute from now', '%(count)s minutes from now', count
            ) % {'count': count}
        else:
            count = delta.seconds // 60 // 60
            return ungettext(
                'an hour from now', '%(count)s hours from now', count
            ) % {'count': count}
Esempio n. 10
0
    def test_naturalday(self):
        today = datetime.date.today()
        yesterday = today - datetime.timedelta(days=1)
        tomorrow = today + datetime.timedelta(days=1)
        someday = today - datetime.timedelta(days=10)
        notdate = "I'm not a date value"

        test_list = (today, yesterday, tomorrow, someday, notdate, None)
        someday_result = defaultfilters.date(someday)
        result_list = (_('today'), _('yesterday'), _('tomorrow'),
                       someday_result, "I'm not a date value", None)
        self.humanize_tester(test_list, result_list, 'naturalday')
Esempio n. 11
0
 def P(self):
     """
     Time, in 12-hour hours, minutes and 'a.m.'/'p.m.', with minutes left off
     if they're zero and the strings 'midnight' and 'noon' if appropriate.
     Examples: '1 a.m.', '1:30 p.m.', 'midnight', 'noon', '12:30 p.m.'
     Proprietary extension.
     """
     if self.data.minute == 0 and self.data.hour == 0:
         return _('midnight')
     if self.data.minute == 0 and self.data.hour == 12:
         return _('noon')
     return '%s %s' % (self.f(), self.a())
Esempio n. 12
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::

        (r'^(?P<path>.*)$', 'djangocg.views.static.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(unquote(path))
    path = path.lstrip('/')
    newpath = ''
    for part in path.split('/'):
        if not part:
            # Strip empty path components.
            continue
        drive, part = os.path.splitdrive(part)
        head, part = os.path.split(part)
        if part in (os.curdir, os.pardir):
            # Strip '.' and '..' in path.
            continue
        newpath = os.path.join(newpath, part).replace('\\', '/')
    if newpath and path != newpath:
        return HttpResponseRedirect(newpath)
    fullpath = os.path.join(document_root, newpath)
    if os.path.isdir(fullpath):
        if show_indexes:
            return directory_index(newpath, fullpath)
        raise Http404(_("Directory indexes are not allowed here."))
    if not os.path.exists(fullpath):
        raise Http404(_('"%(path)s" does not exist') % {'path': fullpath})
    # Respect the If-Modified-Since header.
    statobj = os.stat(fullpath)
    mimetype, encoding = mimetypes.guess_type(fullpath)
    mimetype = mimetype or 'application/octet-stream'
    if not was_modified_since(request.META.get('HTTP_IF_MODIFIED_SINCE'),
                              statobj.st_mtime, statobj.st_size):
        return HttpResponseNotModified()
    with open(fullpath, 'rb') as f:
        response = HttpResponse(f.read(), content_type=mimetype)
    response["Last-Modified"] = http_date(statobj.st_mtime)
    if stat.S_ISREG(statobj.st_mode):
        response["Content-Length"] = statobj.st_size
    if encoding:
        response["Content-Encoding"] = encoding
    return response
Esempio n. 13
0
def logout(request, next_page=None,
           template_name='registration/logged_out.html',
           redirect_field_name=REDIRECT_FIELD_NAME,
           current_app=None, extra_context=None):
    """
    Logs out the user and displays 'You are logged out' message.
    """
    auth_logout(request)
    redirect_to = request.REQUEST.get(redirect_field_name, '')
    if redirect_to:
        netloc = urlparse(redirect_to)[1]
        # Security check -- don't allow redirection to a different host.
        if not (netloc and netloc != request.get_host()):
            return HttpResponseRedirect(redirect_to)

    if next_page is None:
        current_site = get_current_site(request)
        context = {
            'site': current_site,
            'site_name': current_site.name,
            'title': _('Logged out')
        }
        if extra_context is not None:
            context.update(extra_context)
        return TemplateResponse(request, template_name, context,
                                current_app=current_app)
    else:
        # Redirect to this page until the session has been cleared.
        return HttpResponseRedirect(next_page or request.path)
Esempio n. 14
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,
     }
Esempio n. 15
0
    def render(self, name, value, attrs=None):
        rel_to = self.rel.to
        if attrs is None:
            attrs = {}
        extra = []
        if rel_to in self.admin_site._registry:
            # The related object is registered with the same AdminSite
            related_url = reverse('admin:%s_%s_changelist' %
                                    (rel_to._meta.app_label,
                                    rel_to._meta.module_name),
                                    current_app=self.admin_site.name)

            params = self.url_parameters()
            if params:
                url = '?' + '&amp;'.join(['%s=%s' % (k, v) for k, v in params.items()])
            else:
                url = ''
            if "class" not in attrs:
                attrs['class'] = 'vForeignKeyRawIdAdminField' # The JavaScript code looks for this hook.
            # TODO: "lookup_id_" is hard-coded here. This should instead use
            # the correct API to determine the ID dynamically.
            extra.append('<a href="%s%s" class="related-lookup" id="lookup_id_%s" onclick="return showRelatedObjectLookupPopup(this);"> '
                            % (related_url, url, name))
            extra.append('<img src="%s" width="16" height="16" alt="%s" /></a>'
                            % (static('admin/img/selector-search.gif'), _('Lookup')))
        output = [super(ForeignKeyRawIdWidget, self).render(name, value, attrs)] + extra
        if value:
            output.append(self.label_for_value(value))
        return mark_safe(''.join(output))
Esempio n. 16
0
    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 = queryset or self.get_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(BaseDetailView, self).get_object(queryset=qs)
Esempio n. 17
0
    def get_dated_queryset(self, ordering=None, **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 ordering is not None:
            qs = qs.order_by(ordering)

        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 = len(qs) == 0 if paginate_by is None else not qs.exists()
            if is_empty:
                raise Http404(_("No %(verbose_name_plural)s available") % {
                        'verbose_name_plural': force_text(qs.model._meta.verbose_name_plural)
                })

        return qs
Esempio n. 18
0
def validate_ipv46_address(value):
    try:
        validate_ipv4_address(value)
    except ValidationError:
        try:
            validate_ipv6_address(value)
        except ValidationError:
            raise ValidationError(_('Enter a valid IPv4 or IPv6 address.'), code='invalid')
Esempio n. 19
0
 def formfield(self, **kwargs):
     defaults = {
         'error_messages': {
             'invalid': _('Enter only digits separated by commas.'),
         }
     }
     defaults.update(kwargs)
     return super(CommaSeparatedIntegerField, self).formfield(**defaults)
Esempio n. 20
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.module_name)
                    model_dict = {
                        'name': capfirst(model._meta.verbose_name_plural),
                        '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': app_label.title(),
                            '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'])

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

        context = {
            'title': _('Site administration'),
            'app_list': app_list,
        }
        context.update(extra_context or {})
        return TemplateResponse(request, [
            self.index_template or 'admin/index.html',
        ], context, current_app=self.name)
Esempio n. 21
0
 def get_unique_error_message(self, unique_check):
     if len(unique_check) == 1:
         return ugettext("Please correct the duplicate data for %(field)s.") % {
             "field": unique_check[0],
         }
     else:
         return ugettext("Please correct the duplicate data for %(field)s, "
             "which must be unique.") % {
                 "field": get_text_list(unique_check, six.text_type(_("and"))),
             }
Esempio n. 22
0
 def test_unusable_password(self):
     user = User.objects.create_user('testuser', '*****@*****.**', 'test')
     data = {"email": "*****@*****.**"}
     form = PasswordResetForm(data)
     self.assertTrue(form.is_valid())
     user.set_unusable_password()
     user.save()
     form = PasswordResetForm(data)
     self.assertFalse(form.is_valid())
     self.assertEqual(form["email"].errors,
                      [_("The user account associated with this e-mail address cannot reset the password.")])
Esempio n. 23
0
def ordinal(value):
    """
    Converts an integer to its ordinal as a string. 1 is '1st', 2 is '2nd',
    3 is '3rd', etc. Works for any integer.
    """
    try:
        value = int(value)
    except (TypeError, ValueError):
        return value
    suffixes = (_('th'), _('st'), _('nd'), _('rd'), _('th'), _('th'), _('th'), _('th'), _('th'), _('th'))
    if value % 100 in (11, 12, 13): # special case
        return "%d%s" % (value, suffixes[0])
    return "%d%s" % (value, suffixes[value % 10])
Esempio n. 24
0
 def paginate_queryset(self, queryset, page_size):
     """
     Paginate the queryset, if needed.
     """
     paginator = self.get_paginator(queryset, page_size, allow_empty_first_page=self.get_allow_empty())
     page = self.kwargs.get('page') or self.request.GET.get('page') 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:
         raise Http404(_('Invalid page (%(page_number)s)') % {
                             'page_number': page_number
         })
Esempio n. 25
0
def feed(request, url, feed_dict=None):
    """Provided for backwards compatibility."""
    if not feed_dict:
        raise Http404(_("No feeds are registered."))

    try:
        slug, param = url.split('/', 1)
    except ValueError:
        slug, param = url, ''

    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)
Esempio n. 26
0
    def app_index(self, request, app_label, extra_context=None):
        user = request.user
        has_module_perms = user.has_module_perms(app_label)
        app_dict = {}
        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('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_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': 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 = {
            'title': _('%s administration') % capfirst(app_label),
            'app_list': [app_dict],
        }
        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)
Esempio n. 27
0
 def get_as_text(self):
     """
     Return this comment as plain text.  Useful for emails.
     """
     d = {
         'user': self.user or self.name,
         'date': self.submit_date,
         'comment': self.comment,
         'domain': self.site.domain,
         'url': self.get_absolute_url()
     }
     return _('Posted by %(user)s at %(date)s\n\n%(comment)s\n\nhttp://%(domain)s%(url)s') % d
Esempio n. 28
0
    def unique_error_message(self, model_class, unique_check):
        opts = model_class._meta
        model_name = capfirst(opts.verbose_name)

        # A unique field
        if len(unique_check) == 1:
            field_name = unique_check[0]
            field = opts.get_field(field_name)
            field_label = capfirst(field.verbose_name)
            # Insert the error into the error dict, very sneaky
            return field.error_messages["unique"] % {
                "model_name": six.text_type(model_name),
                "field_label": six.text_type(field_label),
            }
        # unique_together
        else:
            field_labels = [capfirst(opts.get_field(f).verbose_name) for f in unique_check]
            field_labels = get_text_list(field_labels, _("and"))
            return _("%(model_name)s with this %(field_label)s already exists.") % {
                "model_name": six.text_type(model_name),
                "field_label": six.text_type(field_labels),
            }
Esempio n. 29
0
def apnumber(value):
    """
    For numbers 1-9, returns the number spelled out. Otherwise, returns the
    number. This follows Associated Press style.
    """
    try:
        value = int(value)
    except (TypeError, ValueError):
        return value
    if not 0 < value < 10:
        return value
    return (_('one'), _('two'), _('three'), _('four'), _('five'), _('six'), _('seven'), _('eight'), _('nine'))[value-1]
Esempio n. 30
0
 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