示例#1
0
 def display_active(self, instance):
     if not instance.is_active:
         return '<img src="%s" alt="False">' % static('admin/img/icon-no.gif')
     elif not instance.account.is_active:
         msg = _("Account disabled")
         return '<img src="%s" alt="False" title="%s">' % (static('admin/img/icon-unknown.gif'), msg)
     return '<img src="%s" alt="False">' % static('admin/img/icon-yes.gif')
示例#2
0
def contact(request):
    is_recaptcha_valid_result = None
    if request.method == 'POST':
        form = ContactMessageForm(request.POST)
        is_recaptcha_valid_result = is_recaptcha_valid(request)
        if form.is_valid() and is_recaptcha_valid_result:
            contact_message = form.save()
            contact_message.send()
            return render(request, 'contact_success.html.jinja2', {
                # SEM metas
                'title': 'Contact the authors',
                'description': """Contact the authors of this anthology through either plain old email, twitter or the provided
                form.""",
                'image': static('ftatr/images/rocking-chair-icon-540x540.png'),
            })
    else:
        form = ContactMessageForm()
    return render(request, 'contact.html.jinja2', {
        # SEM metas
        'title': 'Contact the authors',
        'description': """Contact the authors of this anthology through either plain old email, twitter or the provided
        form.""",
        'image': static('ftatr/images/rocking-chair-icon-540x540.png'),
        # Page content
        'form': form,
        'is_recaptcha_valid': is_recaptcha_valid_result
    })
def make_badge(project, badge_class="oh-badge"):
    """
    Return HTML for a badge.
    """
    if project == "public_data":
        badge_data = {
            "name": "Public Data Sharing",
            "static_url": static("images/public-data-sharing-badge.png"),
            "badge_class": badge_class,
            "href": reverse("public-data:home"),
        }
    else:
        try:
            badge_url = project.badge_image.url
        except ValueError:
            badge_url = static("images/default-badge.png")
        badge_data = {
            "name": project.name,
            "badge_class": badge_class,
            "static_url": badge_url,
            "href": reverse("activity-management", kwargs={"source": project.slug}),
        }

    return mark_safe(
        """<a href="{href}" class="{badge_class}">
            <img class="{badge_class}"
              src="{static_url}" alt="{name}" title="{name}">
           </a>""".format(
            **badge_data
        )
    )
示例#4
0
def webmanifest(request):
    return HttpResponse(
        """{
    "name": "",
    "short_name": "",
    "icons": [
        {
            "src": "%s",
            "sizes": "192x192",
            "type": "image/png"
        },
        {
            "src": "%s",
            "sizes": "512x512",
            "type": "image/png"
        }
    ],
    "theme_color": "#3b1c4a",
    "background_color": "#3b1c4a",
    "display": "standalone"
}""" % (
            static('pretixbase/img/icons/android-chrome-192x192.png'),
            static('pretixbase/img/icons/android-chrome-512x512.png'),
        ), content_type='text/json'
    )
示例#5
0
 def render(self, name, value, attrs=None):
     if value is None:
         value = ''
     final_attrs = self.build_attrs(attrs, name=name)
     js_attrs = {}
     for key in ('first_day', 'format', 'hide_on_select'):
         js_attrs[key] = final_attrs[key]
         del final_attrs[key]
     if value != '':
         final_attrs['value'] = force_text(self._format_value(value))
     if 'class' in final_attrs:
         final_attrs['class'] += ' pickMeUp_datepicker'
     else:
         final_attrs['class'] = ' pickMeUp_datepicker'
     return """<script src="%s"></script>
         <input %s />
         <script>
             $(document).ready(function () {
                 if (! $('#pickMeUpMinStyles').length) {
                     $(document).find('head')
                         .append('<link rel="stylesheet" href="%s"/>');
                 }
                 $('.pickMeUp_datepicker').pickmeup(%s);
             });
         </script>""" % (
         static('js/jquery.pickmeup.min.js'),
         flatatt(final_attrs),
         static('css/pickmeup.min.css'),
         str(js_attrs),
     )
示例#6
0
 def display_active(self, instance):
     if not instance.is_active:
         return '<img src="%s" alt="False">' % static('admin/img/icon-no.svg')
     elif not instance.account.is_active:
         msg = _("Account disabled")
         return '<img style="width:13px" src="%s" alt="False" title="%s">' % (static('admin/img/inline-delete.svg'), msg)
     return '<img src="%s" alt="False">' % static('admin/img/icon-yes.svg')
示例#7
0
def management_list_users(request, eid):
    e = get_object_or_404(Event, id=eid)
    ret = {}
    if request.method == "OPTIONS":
        # Reg
        if e.gestion == Event.GESTION_NOLIMIT:
            already_in_list = []
            ret['reg'] = []
            for ins in Inscription.objects.filter(event=e).select_related("user__profile").select_related('event').select_related("user__contribution").annotate(null_nick=Count('user__profile__nickname')).order_by('null_nick', '-user__profile__nickname', '-user__last_name', '-user__first_name', '-user__username').reverse():
                ret['reg'].append({
                    "display_name": str(ins.user.profile),
                    "picture": ins.user.profile.get_picture_url(),
                    "color": "bg-blue" if ins.in_date is not None else "bg-green" if is_contributor(ins.user) else "bg-red",
                    "type": "reg",
                    "id": ins.id,
                    "user": False,
                })
                already_in_list.append(str(ins.user.profile))
            for user in User.objects.all().select_related('profile'):
                if str(user.profile) not in already_in_list:
                    ret['reg'].append({
                        "display_name": str(user.profile),
                        "picture": user.profile.get_picture_url(),
                        "color": "bg-green" if is_contributor(user) else "bg-red",
                        "type": "reg",
                        "id": user.id,
                        "user": True,
                        'username': user.username,
                    })
        else:
            ret['reg'] = [{
                "display_name": str(ins.user.profile),
                'username': ins.user.username,
                "picture": ins.user.profile.get_picture_url(),
                "color": "bg-blue" if ins.in_date is not None else "bg-green" if is_contributor(ins.user) else "bg-red",
                "type": "reg",
                "id": ins.id,
                "formula": ins.formula.name if ins.formula else None,
                "formula_price": (ins.formula.price_contributor if is_contributor(ins.user) else ins.formula.price_non_contributor) if ins.formula else None,
            } for ins in Inscription.objects.filter(event=e).select_related("user__profile").select_related('event').select_related("user__contribution").annotate(null_nick=Count('user__profile__nickname')).order_by('null_nick', '-user__profile__nickname', '-user__last_name', '-user__first_name', '-user__username').reverse()]

        ret['ext_reg'] = [{
            "display_name": "{} {} ({})".format(ins.last_name, ins.first_name, ins.via.name),
            "picture": static('images/default_user_icon.png'),
            "color": "bg-blue" if ins.in_date is not None else "",
            "type": "ext_reg",
            "id": ins.id,
            "formula": ins.formula.name if ins.formula else None,
            "formula_price": ins.formula.price_non_contributor if ins.formula else None,
        } for ins in ExternInscription.objects.filter(event=e).select_related('event').select_related('via').order_by('last_name', 'first_name')]
        ret['invits'] = [{
            "display_name": "{} {} (invité par {})".format(ins.first_name, ins.last_name, str(ins.user.profile)),
            "picture": static('images/default_user_icon.png'),
            "color": "bg-blue" if ins.in_date is not None else "",
            "type": "invit",
            "id": ins.id,
            "formula": ins.formula.name if ins.formula else None,
            "formula_price": ins.formula.price_non_contributor if ins.formula else None,
        } for ins in Invitation.objects.filter(event=e).select_related('event').select_related('user__profile').order_by('last_name', 'first_name')]
        return JsonResponse(ret)
示例#8
0
def nvd3_static(use_cdnjs=False):
    """
    Load the required JavaScript and CSS files.

    Usage::

        <html>
        <head>
            ...
            {# serve the static files yourself... #}
            {% nvd3_static %}
            {# ...or use cdnjs #}
            {% nvd3_static use_cdnjs=True %}
            ...
        </head>
        <body>
            ...
    """

    if use_cdnjs:
        d3js = JS_TAG.format(nvd3.D3)
        nvd3js = JS_TAG.format(nvd3.NVD3)
        cssjs = CSS_TAG.format(nvd3.NVD3_CSS)
    else:
        d3js = JS_TAG.format(static("django_nvd3/d3.min.js"))
        nvd3js = JS_TAG.format(static("django_nvd3/nv.d3.min.js"))
        cssjs = CSS_TAG.format(static("django_nvd3/nv.d3.min.css"))
    return mark_safe("\n".join([d3js, nvd3js, cssjs]))
示例#9
0
def index(request):
    javascript_includes = []
    stylesheet_includes = []
    orchestra_arguments = {
        'angular_modules': [],
        'angular_directives': defaultdict(lambda: defaultdict(lambda: {}))}

    for step in Step.objects.filter(is_human=True):
        # Preserve js and stylesheet order while removing duplicates
        for js in step.user_interface.get('javascript_includes', []):
            static_js = _get_script_tag(static(js))
            if static_js not in javascript_includes:
                javascript_includes.append(static_js)
        for style in step.user_interface.get('stylesheet_includes', []):
            static_style = _get_style_tag(static(style))
            if static_style not in stylesheet_includes:
                stylesheet_includes.append(static_style)

        if step.user_interface.get('angular_module'):
            orchestra_arguments['angular_modules'].append(
                step.user_interface['angular_module'])

        if step.user_interface.get('angular_directive'):
            orchestra_arguments['angular_directives'][
                step.workflow_version.workflow.slug][
                    step.workflow_version.slug][step.slug] = (
                        step.user_interface['angular_directive'])

    return render(request, 'orchestra/index.html', {
        'javascript_includes': javascript_includes,
        'stylesheet_includes': stylesheet_includes,
        'orchestra_arguments': json.dumps(orchestra_arguments)})
示例#10
0
def storage_img_preview(request, namespace=None):
    base_path = config.get_base_path(namespace)
    path = request.GET.get('path')
    if path.startswith('/'):
        path = path[1:]
    if not path:
        return HttpResponseRedirect(static('file_browser/img/types/img.png'))
    file_path = os.path.join(base_path, path).encode('utf-8')
    if not os.path.exists(file_path):
        return HttpResponseRedirect(static('file_browser/img/types/img.png'))

    try:
        image = Image.open(file_path)
        image.load()
        image.thumbnail((200, 64), Image.ANTIALIAS)
    except Exception:
        return HttpResponseRedirect(static('file_browser/img/types/img.png'))

    if file_path.lower().endswith('jpg') or file_path.lower().endswith('jpeg'):
        response = HttpResponse(content_type='image/jpeg')
        image.save(response, 'JPEG', quality=85)
    else:
        response = HttpResponse(content_type='image/png')
        image.save(response, 'PNG')
    return response
示例#11
0
 def display_used(self, rdata):
     update = ""
     history = ""
     if rdata.pk:
         context = {
             "title": _("Update"),
             "url": reverse("admin:resources_resourcedata_monitor", args=(rdata.pk,)),
             "image": '<img src="%s"></img>' % static("orchestra/images/reload.png"),
         }
         update = '<a href="%(url)s" title="%(title)s">%(image)s</a>' % context
         context.update(
             {
                 "title": _("Show history"),
                 "image": '<img src="%s"></img>' % static("orchestra/images/history.png"),
                 "url": reverse("admin:resources_resourcedata_show_history", args=(rdata.pk,)),
                 "popup": 'onclick="return showAddAnotherPopup(this);"',
             }
         )
         history = '<a href="%(url)s" title="%(title)s" %(popup)s>%(image)s</a>' % context
     if rdata.used is not None:
         used_url = reverse("admin:resources_resourcedata_used_monitordata", args=(rdata.pk,))
         used = '<a href="%s">%s %s</a>' % (used_url, rdata.used, rdata.unit)
         return " ".join(map(str, (used, update, history)))
     if rdata.resource.monitors:
         return _("Unknonw %s %s") % (update, history)
     return _("No monitor")
示例#12
0
文件: tags.py 项目: antleocar/testing
def avatar(avatar):
    if avatar:
        if default_storage.exists(avatar.name):
            return avatar.url
        else:
            return static("webapp/image/logo_mini.png")
    else:
        return static("webapp/image/logo_mini.png")
示例#13
0
def get_icon_for_namespace(namespace):
    """ Return the static path to the icon associated with given namespace
    """
    try:
        icon = NamespaceIcon.objects.get(namespace=namespace)
    except:
        return static("ns_icon/octalpus.png")
    return static("ns_icon/%s" % (icon.icon))
示例#14
0
def pluginDownloadUrl(os):
    tmpl = '<a href="{url}" class="btn btn-success">' + _('Download UDS Plugin for') + ' {os}</a>'
    if os == 'windows':
        return tmpl.format(url=static('client/UDSClientSetup.exe'), os='Windows')
    elif os == 'linux':
        return '2'
    else:
        return tmpl.format(url=static('client/UDSClient.dmg'), os='Mac OSX')
示例#15
0
    def _profile_image_url(self):
        if self.profile_image:
            return self.profile_image.url

        if self.is_boy:
            return static('img/profile/boy.jpg')
        else:
            return static('img/profile/girl.jpg')
示例#16
0
 def get_image_url(self):
     if self.user.is_active:
         if self.image and hasattr(self.image, "url"):
             img_url = self.image.url
         else:
             img_url = static("series/anonymous_user.png")
     else:
         img_url = static("series/deleted_user.png")
     return img_url
示例#17
0
文件: views.py 项目: rkorkosz/seo
 def get_context_data(self, **kwargs):
     context = super(IndexView, self).get_context_data(**kwargs)
     with open(os.path.join(settings.BASE_DIR, 'manifest.json'), 'r') as manifest:
         m = json.loads(manifest.read())
         context.update({
             'seo_js': static(m.get('js/seo.min.js', 'js/seo.min.js')),
             'seo_css': static(m.get('less/main.css', 'less/main.css'))
         })
     return context
示例#18
0
 def render(self, name, value, attrs=None):
     output = []
     if value and hasattr(value, "url"):
         output.append(('<div style="float:left"><a target="_blank" href="%s">'
                        '<img src="%s" style="height: 120px;" /></a><br> '
                        % (static(value.url), static(value.url))))
     output.append(super(AdminImageWidget, self).render(name, value, attrs))
     output.append('</div>')
     return mark_safe(u''.join(output))
示例#19
0
def sign_img(value):
    r = ''
    if value and value>=0:
        i = int(value/30)
        r = static('clevenus/signs/'+SIGN_SVG[i])
    else:
        r = static('clevenus/signs/00-unknown.svg')


    return r
示例#20
0
文件: models.py 项目: imclab/Franklin
 def get_flag_image(self, user):
     completed = user.is_authenticated() and user.has_completed_skill(self)
     if not completed and self.normal_flag_image:
         return self.normal_flag_image.url
     elif completed and self.completed_flag_image:
         return self.completed_flag_image.url
     elif completed:
         return static('images/skill-flag-red.png')
     else:
         return static('images/skill-flag-gray.png')
示例#21
0
文件: admin.py 项目: agagata/duh-web
 def is_claimed(self, obj):
     """
     A boolean-style icon with a link to the claimed invitation if it exists.
     """
     try:
         claimed = obj.claimed
     except ClaimedInvitation.DoesNotExist:
         return format_html('<img src="{}" alt="False" />', static('admin/img/icon-no.svg'))
     return format_html('<a href="{}"><img src="{}" alt="True" /></a>',
         reverse('admin:slakslakslak_claimedinvitation_change', args=[claimed.pk]),
         static('admin/img/icon-yes.svg'),
     )
示例#22
0
def test_build_absolute_uri(site_settings, settings):
    # Case when we are using external service for storing static files,
    # eg. Amazon s3
    url = "https://example.com/static/images/image.jpg"
    assert build_absolute_uri(location=url) == url

    # Case when static url is resolved to relative url
    logo_url = build_absolute_uri(static("images/logo-light.svg"))
    protocol = "https" if settings.ENABLE_SSL else "http"
    current_url = "%s://%s" % (protocol, site_settings.site.domain)
    logo_location = urljoin(current_url, static("images/logo-light.svg"))
    assert logo_url == logo_location
示例#23
0
def webp_static(context, static_path):
    if not context.get("is_supports_webp", False):
        return static(static_path)

    full_path = os.path.join(settings.STATICFILES_DIRS[0], static_path)
    original_ext = os.path.splitext(full_path)[1]
    webp_path = os.path.splitext(full_path)[0] + ".webp"
    if not os.path.isfile(webp_path):
        image = Image.open(full_path)
        image.save(webp_path, "WEBP", quality=90)

    return static(static_path.replace(original_ext, ".webp"))
示例#24
0
def version(path_string):
    try:
        if path_string in version_cache:
            mtime = version_cache[path_string]
        else:
            mtime = os.path.getmtime(
                        os.path.join(settings.STATIC_ROOT, path_string)
                    )
            version_cache[path_string] = mtime

        return static('%s?%d' %(path_string,mtime) )
    except:
        return static('%s?%s' %(path_string,datetime.now().strftime('%s')))
    def add_resource_urls(self, fragment):
        """
        Adds URLs for JS and CSS resources that this XBlock depends on to `fragment`.
        """
        # Head dependencies
        for vendor_js_file in self.vendor_js_dependencies():
            fragment.add_resource_url(static(vendor_js_file), "application/javascript", "head")

        for css_file in self.css_dependencies():
            fragment.add_css_url(static(css_file))

        # Body dependencies
        for js_file in self.js_dependencies():
            fragment.add_javascript_url(static(js_file))
示例#26
0
def add_gdpr_consent_resources(context, content):
    if not valid_view(context):
        return

    request = context["request"]
    shop = get_shop(request)
    gdpr_settings = GDPRSettings.get_for_shop(shop)

    # GDPR not enabled, nothing to do
    if not gdpr_settings.enabled:
        return

    # always add styles
    add_resource(context, "head_end", static("shuup-gdpr.css"))

    user = request.user
    if not user.is_anonymous() and should_reconsent_privacy_policy(shop, user):
        consent_page = get_privacy_policy_page(shop)
        render_context = {
            "request": request,
            "csrf_token": context["csrf_token"],
            "url": "/%s" % consent_page.url,
            "accept_url": reverse("shuup:gdpr_policy_consent", kwargs=dict(page_id=consent_page.id))
        }
        update_resource = InlineMarkupResource(
            loader.render_to_string("shuup/gdpr/privacy_policy_update.jinja", context=render_context)
        )
        add_resource(context, "body_end", update_resource)

    # consent already added
    if settings.SHUUP_GDPR_CONSENT_COOKIE_NAME in request.COOKIES:
        return

    gdpr_documents = []
    if has_installed("shuup.simple_cms"):
        gdpr_documents = get_active_consent_pages(shop)

    render_context = {
        "request": request,
        "csrf_token": context["csrf_token"],
        "gdpr_settings": gdpr_settings,
        "gdpr_documents": gdpr_documents,
        "gdpr_cookie_categories": GDPRCookieCategory.objects.filter(shop=shop)
    }
    html_resource = InlineMarkupResource(
        loader.render_to_string("shuup/gdpr/gdpr_consent.jinja", context=render_context)
    )
    add_resource(context, "body_end", html_resource)
    add_resource(context, "body_end", static("shuup-gdpr.js"))
示例#27
0
def context_processor(request):
    ''' theming template context processor '''
    theme = thememanager.get_current_theme()
    theme_url = static(os.path.join(settings.THEMING_URL, theme.slug)).replace('\\', '/')
    return {
        'theme_url': theme_url,
    }
示例#28
0
def get_gravatar_url(email: str, **options) -> str:
    """Get the gravatar url associated to an email.

    :param options: Additional options to gravatar.
    - `default` defines what image url to show if no gravatar exists
    - `size` defines the size of the avatar.

    :return: Gravatar url.
    """

    params = copy.copy(options)

    default_avatar = getattr(settings, "GRAVATAR_DEFAULT_AVATAR", None)
    default_size = getattr(settings, "GRAVATAR_AVATAR_SIZE", None)

    avatar = options.get("default", None)
    size = options.get("size", None)

    if avatar:
        params["default"] = avatar
    elif default_avatar:
        params["default"] = static(default_avatar)

    if size:
        params["size"] = size
    elif default_size:
        params["size"] = default_size

    email_hash = hashlib.md5(email.lower().encode()).hexdigest()
    url = GRAVATAR_BASE_URL.format(email_hash, urlencode(params))

    return url
示例#29
0
文件: views.py 项目: tjcsl/ion
def get_bg_pattern():
    """Choose a background pattern image.

    One will be selected at random.

    """
    files = [
        "brushed.png",
        "concrete_seamless.png",
        "confectionary.png",
        "contemporary_china.png",
        "crossword.png",
        # "fresh_snow.png",
        "greyzz.png",
        "light_grey.png",
        "p6.png",
        "pixel_weave.png",
        "ps_neutral.png",
        "pw_pattern.png",
        "sos.png",
        "squairy_light.png",
        # "squared_metal.png"
    ]
    file_path = "img/patterns/"

    return static(file_path + random.choice(files))
    def render(self, name, value, attrs=None):
        """ Render the button.
        
        If given an ``onClick`` attribute, id of the widget will be passed in to
        the function parameters.
        
        :param name: The name of the widget
        :type name: str
        
        :param value: The value of the widget (unused).
        :type value: void
        
        :param attrs: Attributes for the widget.
        :type attrs: dict
        """
        if 'id' in attrs and self.on_click_method:
            attrs.update({
                'onClick' : str(self.on_click_method%{'id' : attrs['id'],}),
                'type' : 'button',
            })
            
        # It's ugly, but first we need to prepend some javascript.
        js = static(STATIC_JS)
        
        logger.debug(js)
        
        s = """<script type="text/javascript"></script>
<script type="text/javascript" src="%s"></script>"""%js
        
        return mark_safe(s + "<button %s>%s</button>"%(html_attrs(attrs),
                                                   self.label))
示例#31
0
def make_path(mapping, *path):
    staticmap = getattr(settings, 'STATICFILES_DART', DEFAULT_SETTINGS)
    root = staticmap.get(mapping, DEFAULT_SETTINGS[mapping])
    return static(urljoin(root, *path))
示例#32
0
def admin_boolean_icon(val):
    """Admin icon wrapper."""
    ext = "svg"
    icon_url = static("admin/img/icon-{0}.{1}".format(TYPE_MAPPING[val], ext))
    return mark_safe('<img src="{url}" alt="{text}" title="{text}" />'.format(
        url=icon_url, text=NAME_MAPPING[val]))
def editor_js():
    html = '<script type="text/javascript" src="{}"></script>'.format(
        static('wagtailautocomplete/dist.js'))
    return format_html(html)
示例#34
0
 def test_static_proxy_with_static_url_with_full_host(self):
     from django.templatetags.static import static
     querystring = urlencode([('u', static("test/image.jpg"))])
     self._static_proxy(querystring)
示例#35
0
def evileg_core_icons_min_css():
    return static("css/materialdesignicons.min.css")
示例#36
0
def evileg_core_markdown_min_js():
    return static("js/markdown.min.js")
示例#37
0
def udsJs(request: 'HttpRequest') -> str:
    auth_host = request.META.get('HTTP_HOST') or request.META.get(
        'SERVER_NAME'
    ) or 'auth_host'  # Last one is a placeholder in case we can't locate host name

    role: str = 'user'
    user: typing.Optional['User'] = request.user

    if user:
        role = 'staff' if user.isStaff(
        ) and not user.is_admin else 'admin' if user.is_admin else 'user'

    profile: typing.Dict[str, typing.Any] = {
        'user': user.name if user else None,
        'role': role,
    }

    # Gets csrf token
    csrf_token = csrf.get_token(request)
    if csrf_token is not None:
        csrf_token = str(csrf_token)

    tag = request.session.get('tag', None)
    logger.debug('Tag config: %s', tag)
    if GlobalConfig.DISALLOW_GLOBAL_LOGIN.getBool():
        try:
            # Get authenticators with auth_host or tag. If tag is None, auth_host, if exists
            # tag, later will remove "auth_host"
            authenticators = Authenticator.objects.filter(
                small_name__in=[auth_host, tag])[:]
        except Exception as e:
            authenticators = []
    else:
        authenticators = Authenticator.objects.all().exclude(visible=False)

    # logger.debug('Authenticators PRE: %s', authenticators)

    if tag and authenticators:  # Refilter authenticators, visible and with this tag if required
        authenticators = [x for x in authenticators if x.small_name == tag]

    if not authenticators:
        try:
            authenticators = [Authenticator.objects.order_by('priority')[0]]
        except Exception:  # There is no authenticators yet...
            authenticators = []

    # logger.debug('Authenticators: %s', authenticators)

    # the auths for client
    def getAuthInfo(auth: Authenticator):
        theType = auth.getType()
        return {
            'id': auth.uuid,
            'name': auth.name,
            'label': auth.small_name,
            'priority': auth.priority,
            'is_custom': theType.isCustom()
        }

    config = {
        'version':
        VERSION,
        'version_stamp':
        VERSION_STAMP,
        'language':
        get_language(),
        'available_languages': [{
            'id': k,
            'name': gettext(v)
        } for k, v in settings.LANGUAGES],
        'authenticators':
        [getAuthInfo(auth) for auth in authenticators if auth.getType()],
        'tag':
        tag,
        'os':
        request.os['OS'],
        'csrf_field':
        CSRF_FIELD,
        'csrf':
        csrf_token,
        'image_size':
        Image.MAX_IMAGE_SIZE,
        'experimental_features':
        GlobalConfig.EXPERIMENTAL_FEATURES.getBool(),
        'reload_time':
        GlobalConfig.RELOAD_TIME.getInt(True),
        'site_name':
        GlobalConfig.SITE_NAME.get(),
        'site_copyright_info':
        GlobalConfig.SITE_COPYRIGHT.get(),
        'site_copyright_link':
        GlobalConfig.SITE_COPYRIGHT_LINK.get(),
        'site_logo_name':
        GlobalConfig.SITE_LOGO_NAME.get(),
        'site_information':
        GlobalConfig.SITE_INFO.get(),
        'site_filter_on_top':
        GlobalConfig.SITE_FILTER_ONTOP.getBool(True),
        'launcher_wait_time':
        5000,
        'messages': {
            # Calendar denied message
            'calendarDenied':
            GlobalConfig.LIMITED_BY_CALENDAR_TEXT.get().strip()
            or gettext('Access limited by calendar')
        },
        'urls': {
            'changeLang':
            reverse('set_language'),
            'login':
            reverse('page.login'),
            'logout':
            reverse('page.logout'),
            'user':
            reverse('page.index'),
            'customAuth':
            reverse('uds.web.views.customAuth', kwargs={'idAuth': ''}),
            'services':
            reverse('webapi.services'),
            'enabler':
            reverse('webapi.enabler',
                    kwargs={
                        'idService': 'param1',
                        'idTransport': 'param2'
                    }),
            'action':
            reverse('webapi.action',
                    kwargs={
                        'idService': 'param1',
                        'actionString': 'param2'
                    }),
            'galleryImage':
            reverse('webapi.galleryImage', kwargs={'idImage': 'param1'}),
            'transportIcon':
            reverse('webapi.transportIcon', kwargs={'idTrans': 'param1'}),
            'static':
            static(''),
            # Launcher URL if exists
            'launch':
            request.session.get('launch', ''),
        }
    }

    info: typing.Optional[typing.MutableMapping] = None
    if user and user.isStaff():
        info = {
            'networks': [n.name for n in Network.networksFor(request.ip)],
            'transports': [
                t.name for t in Transport.objects.all()
                if t.validForIp(request.ip)
            ],
            'ip':
            request.ip,
            'ip_proxy':
            request.ip_proxy
        }

    # all plugins are under url clients...
    plugins = [{
        'url': static('clients/' + url.format(version=CLIENT_VERSION)),
        'description': description,
        'name': name,
        'legacy': legacy,
    } for url, description, name, legacy in (
        ('UDSClientSetup-{version}.exe', gettext('Windows client'), 'Windows',
         False),
        ('UDSClient-{version}.pkg', gettext('Mac OS X client'), 'MacOS',
         False),
        ('udsclient3_{version}_all.deb', gettext('Debian based Linux client') +
         ' ' + gettext('(requires Python-3.6 or newer)'), 'Linux', False),
        ('udsclient3-{version}-1.noarch.rpm',
         gettext('RPM based Linux client (Fedora, Suse, ...)') + ' ' +
         gettext('(requires Python-3.6 or newer)'), 'Linux', False),
        ('udsclient3-{version}.tar.gz',
         gettext('Generic .tar.gz Linux client') + ' ' +
         gettext('(requires Python-3.6 or newer)'), 'Linux', False),
        ('udsclient_{version}_all.deb',
         gettext('Legacy Debian based Python 2.7 Linux client') + ' ' +
         gettext('(requires outdated Python-2.7)'), 'Linux', True),
        ('udsclient-{version}-1.noarch.rpm',
         gettext('Legacy RH based Linux client (Fedora, Centos, Suse, ...)') +
         ' ' + gettext('(requires outdated Python-2.7)'), 'Linux', True),
        ('udsclient-opensuse-{version}-1.noarch.rpm',
         gettext('Legacy OpenSuse based Linux client)') + ' ' +
         gettext('(requires outdated Python-2.7)'), 'Linux', True),
    )]

    actors: typing.List[typing.Dict[str, str]] = []

    if user and user.isStaff():  # Add staff things
        # If is admin (informational, REST api checks users privileges anyway...)
        profile['admin'] = True
        # REST auth
        config['auth_token'] = request.session.session_key
        config['auth_header'] = AUTH_TOKEN_HEADER
        # Actors
        actors = [{
            'url':
            reverse('utility.downloader', kwargs={'idDownload': key}),
            'name':
            val['name'],
            'description':
            gettext(val['comment'])
        } for key, val in downloadsManager().getDownloadables().items()]
        # URLS
        config['urls']['admin'] = reverse('uds.admin.views.index')
        config['urls']['rest'] = reverse('REST', kwargs={'arguments': ''})
        # Admin config
        page_size = GlobalConfig.ADMIN_PAGESIZE.getInt(True)
        # Fix page size to razonable usable values
        page_size = 10 if page_size < 10 else 50 if page_size > 50 else page_size
        config['admin'] = {
            'page_size': page_size,
        }

    errors: typing.List = []
    if 'errors' in request.session:
        errors = request.session['errors']
        del request.session['errors']
        request.session.modified = True  # Ensure saves it

    uds = {
        'profile': profile,
        'config': config,
        'info': info,
        'plugins': plugins,
        'actors': actors,
        'errors': errors,
        'data': request.session.get('data')
    }

    # Reset some 1 time values...
    request.session['launch'] = ''

    return 'var udsData = ' + json.dumps(uds) + ';\n'
示例#38
0
def get_category_pin_url(name):
    if not name:
        name = 'default'
    return static('category_icons/pins/{}_pin.svg'.format(name))
示例#39
0
def favicon(request):
    """Redirect "/favicon.ico" to the favicon in the static files """
    return HttpResponsePermanentRedirect(static("favicon/favicon.ico"))
示例#40
0
def global_admin_css():
    css_files = [static('wagtailcommerce/css/wagtailadmin/core.css')]
    css_includes = format_html_join('\n', '<link rel="stylesheet" href="{}">',
                                    ((filename, ) for filename in css_files))

    return css_includes
示例#41
0
文件: views.py 项目: ryardley/pretix
 def get_default_background(self):
     return static('pretixplugins/badges/badge_default_a6l.pdf')
示例#42
0
"""the_sudoku URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
from django.views.generic import RedirectView
from django.templatetags.static import static

urlpatterns = [
    path('', include('sudoku.urls')),
    path('admin/', admin.site.urls),
    path('favicon.ico/',
         RedirectView.as_view(url=static('the_sudoku/img/logo.svg')))
]
示例#43
0
文件: models.py 项目: open-tribe/web
 def preview_img_url(self):
     if self.preview_img_mode == 'png':
         return self.img_url
     if "https:" in self.image:
         return self.image
     return static(self.image)
示例#44
0
             'productions/js/cowbell/ay_chip.min.js',
             'productions/js/cowbell/vtx.min.js'
         ])),
 'mp3': ('Cowbell.Player.Audio', {},
         Media(js=['productions/js/cowbell/cowbell.min.js'])),
 'ogg': ('Cowbell.Player.Audio', {},
         Media(js=['productions/js/cowbell/cowbell.min.js'])),
 'wav': ('Cowbell.Player.Audio', {},
         Media(js=['productions/js/cowbell/cowbell.min.js'])),
 'opus': ('Cowbell.Player.Audio', {},
          Media(js=['productions/js/cowbell/cowbell.min.js'])),
 'flac': ('Cowbell.Player.Audio', {},
          Media(js=['productions/js/cowbell/cowbell.min.js'])),
 'openmpt': ('Cowbell.Player.OpenMPT', {
     'pathToLibOpenMPT':
     static('productions/js/cowbell/libopenmpt.js'),
 },
             Media(js=[
                 'productions/js/cowbell/cowbell.min.js',
                 'productions/js/cowbell/openmpt.min.js'
             ])),
 'sid': ('Cowbell.Player.JSSID', {},
         Media(js=[
             'productions/js/cowbell/cowbell.min.js',
             'productions/js/cowbell/jssid.min.js'
         ])),
 'sap': ('Cowbell.Player.ASAP', {},
         Media(js=[
             'productions/js/cowbell/cowbell.min.js',
             'productions/js/cowbell/asap.min.js'
         ])),
示例#45
0
def evileg_core_cropper_min_css():
    return static("css/cropper.min.css")
示例#46
0
 def get_banner_image_url(self):
     if self.banner_image and hasattr(self.banner_image, 'url'):
         return self.banner_image.url
     else:
         return static('img/banner.svg')
示例#47
0
文件: models.py 项目: orbweaver-/web
 def preview_img_url(self):
     if self.preview_img_mode == 'png':
         return self.img_url
     return static(self.image)
示例#48
0
 def get_site_logo_url(self):
     if self.site_logo and hasattr(self.site_logo, 'url'):
         return self.site_logo.url
     else:
         return static('img/default_icon.png')
示例#49
0
 def test_static_proxy_with_host(self):
     querystring = urlencode(
         [('u', static("test/image.jpg"))])
     self._static_proxy(querystring)
示例#50
0
def udsJs(request: 'HttpRequest') -> str:
    auth_host = request.META.get('HTTP_HOST') or request.META.get(
        'SERVER_NAME'
    ) or 'auth_host'  # Last one is a placeholder in case we can't locate host name

    profile = {
        'user': None if not request.user else request.user.name,
        'role':
        'staff' if request.user and request.user.staff_member else 'user',
    }

    # Gets csrf token
    csrf_token = csrf.get_token(request)
    if csrf_token is not None:
        csrf_token = str(csrf_token)

    tag = request.session.get('tag', None)

    if GlobalConfig.DISALLOW_GLOBAL_LOGIN.getBool(False) is True:
        try:
            authenticators = [Authenticator.objects.get(small_name=auth_host)]
        except Exception:
            try:
                authenticators = [
                    Authenticator.objects.order_by('priority')[0].small_name
                ]
            except Exception:  # There is no authenticators yet...
                authenticators = []
    else:
        authenticators = Authenticator.objects.all().exclude(visible=False)

    if tag:
        authenticators = [x for x in authenticators if x.small_name == tag]

    # the auths for client
    def getAuthInfo(auth: Authenticator):
        theType = auth.getType()
        return {
            'id': auth.uuid,
            'name': auth.name,
            'label': auth.small_name,
            'priority': auth.priority,
            'is_custom': theType.isCustom()
        }

    config = {
        'version':
        VERSION,
        'version_stamp':
        VERSION_STAMP,
        'language':
        get_language(),
        'available_languages': [{
            'id': k,
            'name': gettext(v)
        } for k, v in settings.LANGUAGES],
        'authenticators':
        [getAuthInfo(auth) for auth in authenticators if auth.getType()],
        'os':
        request.os['OS'],
        'csrf_field':
        CSRF_FIELD,
        'csrf':
        csrf_token,
        'image_size':
        Image.MAX_IMAGE_SIZE,
        'reload_time':
        GlobalConfig.RELOAD_TIME.getInt(True),
        'site_name':
        GlobalConfig.SITE_NAME.get(),
        'site_copyright_info':
        GlobalConfig.SITE_COPYRIGHT.get(),
        'site_copyright_link':
        GlobalConfig.SITE_COPYRIGHT_LINK.get(),
        'messages': {
            # Calendar denied message
            'calendarDenied':
            GlobalConfig.LIMITED_BY_CALENDAR_TEXT.get().strip()
            or gettext("Access limited by calendar")
        },
        'urls': {
            'changeLang':
            reverse('set_language'),
            'login':
            reverse('page.login'),
            'logout':
            reverse('page.logout'),
            'user':
            reverse('page.index'),
            'customAuth':
            reverse('uds.web.views.customAuth', kwargs={'idAuth': ''}),
            'services':
            reverse('webapi.services'),
            'enabler':
            reverse('webapi.enabler',
                    kwargs={
                        'idService': 'param1',
                        'idTransport': 'param2'
                    }),
            'action':
            reverse('webapi.action',
                    kwargs={
                        'idService': 'param1',
                        'action': 'param2'
                    }),
            'galleryImage':
            reverse('webapi.galleryImage', kwargs={'idImage': 'param1'}),
            'transportIcon':
            reverse('webapi.transportIcon', kwargs={'idTrans': 'param1'}),
            'static':
            static(''),
            # Launcher URL if exists
            'launch':
            request.session.get('launch', ''),
        }
    }

    # all plugins are under url clients...
    plugins = [{
        'url': static('clients/' + url.format(version=CLIENT_VERSION)),
        'description': description,
        'name': name
    } for url, description, name in (
        ('UDSClientSetup-{version}.exe', gettext('Windows client'),
         'Windows'), ('UDSClient-{version}.pkg', gettext('Mac OS X client'),
                      'MacOS'), ('udsclient_{version}_all.deb',
                                 gettext('Debian based Linux client') + ' ' +
                                 gettext('(requires Python-2.7)'), 'Linux'),
        ('udsclient-{version}-1.noarch.rpm',
         gettext('Red Hat based Linux client (RH, Fedora, Centos, ...)') +
         ' ' + gettext('(requires Python-2.7)'),
         'Linux'), ('udsclient-opensuse-{version}-1.noarch.rpm',
                    gettext('Suse based Linux client') + ' ' +
                    gettext('(requires Python-2.7)'),
                    'Linux'), ('udsclient-{version}.tar.gz',
                               gettext('Generic .tar.gz Linux client') + ' ' +
                               gettext('(requires Python-2.7)'), 'Linux'))]

    actors: typing.List[typing.Dict[str, str]] = []

    if profile['role'] == 'staff':  # Add staff things
        # If is admin (informational, REST api checks users privileges anyway...)
        profile['admin'] = True
        # REST auth
        config['auth_token'] = request.session.session_key
        config['auth_header'] = AUTH_TOKEN_HEADER
        # Actors
        actors = [{
            'url':
            reverse('utility.downloader', kwargs={'idDownload': key}),
            'name':
            val['name'],
            'description':
            gettext(val['comment'])
        } for key, val in downloadsManager().getDownloadables().items()]
        # URLS
        config['urls']['admin'] = reverse('uds.admin.views.index')
        config['urls']['rest'] = reverse('REST', kwargs={'arguments': ''})

    errors: typing.List = []
    if 'errors' in request.session:
        errors = request.session['errors']
        del request.session['errors']
        request.session.modified = True  # Ensure saves it

    uds = {
        'profile': profile,
        'config': config,
        'plugins': plugins,
        'actors': actors,
        'errors': errors,
        'data': request.session.get('data')
    }

    # Reset some 1 time values...
    request.session['launch'] = ''

    return 'var udsData = ' + json.dumps(uds) + ';\n'
def editor_css():
    html = '<link rel="stylesheet" type="text/css" href="{}" />'.format(
        static('wagtailautocomplete/dist.css'))
    return format_html(html)
示例#52
0
    def get_context_data(self, **kwargs):
        """ called by the template system to get the context data for the template """
        context = super().get_context_data(**kwargs)

        context['nhb_ver'] = ver = self.functie_nu.nhb_ver

        context['clusters'] = ver.clusters.all()

        if self.functie_nu.nhb_ver.wedstrijdlocatie_set.exclude(
                baan_type=BAAN_TYPE_EXTERN).filter(zichtbaar=True).count() > 0:
            context['accommodatie_details_url'] = reverse(
                'Vereniging:vereniging-accommodatie-details',
                kwargs={'vereniging_pk': ver.pk})

        context['url_externe_locaties'] = reverse(
            'Vereniging:externe-locaties', kwargs={'vereniging_pk': ver.pk})

        if self.rol_nu == Rollen.ROL_SEC or ver.regio.is_administratief:
            # SEC
            comps = list()
            deelcomps = list()
            deelcomps_rk = list()
        else:
            # HWL of WL
            context['toon_competities'] = True

            # if rol_nu == Rollen.ROL_HWL:
            #     context['toon_wedstrijdkalender'] = True

            comps = (Competitie.objects.filter(is_afgesloten=False).order_by(
                'afstand', 'begin_jaar'))

            deelcomps = (DeelCompetitie.objects.filter(
                laag=LAAG_REGIO,
                competitie__is_afgesloten=False,
                nhb_regio=ver.regio).select_related('competitie'))

            deelcomps_rk = (DeelCompetitie.objects.filter(
                laag=LAAG_RK,
                competitie__is_afgesloten=False,
                nhb_rayon=ver.regio.rayon).select_related('competitie'))

            pks = (DeelcompetitieRonde.objects.filter(
                deelcompetitie__is_afgesloten=False,
                plan__wedstrijden__vereniging=ver).values_list(
                    'plan__wedstrijden', flat=True))
            if CompetitieWedstrijd.objects.filter(pk__in=pks).count() > 0:
                context['heeft_wedstrijden'] = True

        # bepaal de volgorde waarin de kaartjes getoond worden
        # 1 - aanmelden
        # 2 - teams regio aanmelden / aanpassen
        # 3 - teams rk
        # 4 - ingeschreven
        # 5 - wie schiet waar (voor inschrijfmethode 1)
        context['kaartjes'] = kaartjes = list()
        prev_jaar = 0
        prev_afstand = 0
        for comp in comps:
            begin_jaar = comp.begin_jaar
            comp.bepaal_fase()

            if prev_jaar != begin_jaar or prev_afstand != comp.afstand:
                if len(kaartjes) and hasattr(kaartjes[-1], 'heading'):
                    # er waren geen kaartjes voor die competitie - meld dat
                    kaartje = SimpleNamespace()
                    kaartje.geen_kaartjes = True
                    kaartjes.append(kaartje)

                # nieuwe heading aanmaken
                kaartje = SimpleNamespace()
                kaartje.heading = comp.beschrijving
                kaartjes.append(kaartje)

                prev_jaar = begin_jaar
                prev_afstand = comp.afstand

            # 1 - leden aanmelden voor de competitie (niet voor de WL)
            if comp.fase < 'F' and self.rol_nu != Rollen.ROL_WL:
                kaartje = SimpleNamespace()
                kaartje.titel = "Aanmelden"
                kaartje.tekst = 'Leden aanmelden voor de %s.' % comp.beschrijving
                kaartje.url = reverse('CompInschrijven:leden-aanmelden',
                                      kwargs={'comp_pk': comp.pk})
                if comp.afstand == '18':
                    kaartje.img = static('plein/badge_nhb_indoor.png')
                else:
                    kaartje.img = static('plein/badge_nhb_25m1p.png')
                if comp.fase < 'B':
                    kaartje.beschikbaar_vanaf = localize(
                        comp.begin_aanmeldingen)
                kaartjes.append(kaartje)

            for deelcomp in deelcomps:
                if deelcomp.competitie == comp:
                    if deelcomp.regio_organiseert_teamcompetitie and 'E' <= comp.fase <= 'F' and 1 <= deelcomp.huidige_team_ronde <= 7:
                        # team invallers opgeven
                        kaartje = SimpleNamespace(
                            titel="Team Invallers",
                            tekst=
                            "Invallers opgeven voor ronde %s van de regiocompetitie voor de %s."
                            % (deelcomp.huidige_team_ronde, comp.beschrijving),
                            url=reverse('CompRegio:teams-regio-invallers',
                                        kwargs={'deelcomp_pk': deelcomp.pk}),
                            icon='how_to_reg')
                        kaartjes.append(kaartje)
                    else:
                        # 2 - teams aanmaken
                        if deelcomp.regio_organiseert_teamcompetitie and comp.fase <= 'E':
                            kaartje = SimpleNamespace()
                            kaartje.titel = "Teams Regio"
                            kaartje.tekst = 'Verenigingsteams voor de regiocompetitie samenstellen voor de %s.' % comp.beschrijving
                            kaartje.url = reverse(
                                'CompRegio:teams-regio',
                                kwargs={'deelcomp_pk': deelcomp.pk})
                            kaartje.icon = 'gamepad'
                            if comp.fase < 'B':
                                kaartje.beschikbaar_vanaf = localize(
                                    comp.begin_aanmeldingen)
                            kaartjes.append(kaartje)
            # for
            del deelcomp

            # 3 - teams RK
            for deelcomp_rk in deelcomps_rk:
                if deelcomp_rk.competitie == comp:
                    if deelcomp_rk.heeft_deelnemerslijst:
                        if 'J' <= comp.fase <= 'K':
                            # RK voorbereidende fase
                            kaartje = SimpleNamespace()
                            kaartje.titel = "Deelnemers RK"
                            kaartje.tekst = "Sporters van de vereniging aan-/afmelden voor het RK van de %s" % comp.beschrijving
                            kaartje.url = reverse(
                                'CompRayon:lijst-rk-ver',
                                kwargs={'rk_deelcomp_pk': deelcomp_rk.pk})
                            kaartje.icon = 'rule'
                            kaartjes.append(kaartje)

                    if 'E' <= comp.fase <= 'K' and self.rol_nu != Rollen.ROL_WL:
                        kaartje = SimpleNamespace()
                        kaartje.titel = "Teams RK"
                        kaartje.tekst = "Verenigingsteams voor de rayonkampioenschappen samenstellen voor de %s." % comp.beschrijving
                        kaartje.url = reverse(
                            'CompRayon:teams-rk',
                            kwargs={'rk_deelcomp_pk': deelcomp_rk.pk})
                        kaartje.icon = 'api'
                        # niet beschikbaar maken tot een paar weken na de eerste regiowedstrijd
                        vanaf = comp.eerste_wedstrijd + datetime.timedelta(
                            days=settings.COMPETITIES_OPEN_RK_TEAMS_DAYS_AFTER)
                        if datetime.date.today() < vanaf:
                            kaartje.beschikbaar_vanaf = localize(vanaf)
                        kaartjes.append(kaartje)
            # for
            del deelcomp_rk

            for deelcomp in deelcomps:
                if deelcomp.competitie == comp:
                    # 4 - ingeschreven
                    if 'B' <= comp.fase <= 'F':  # vanaf RK fase niet meer tonen
                        kaartje = SimpleNamespace()
                        kaartje.titel = "Ingeschreven"
                        kaartje.tekst = "Overzicht ingeschreven leden voor de %s." % comp.beschrijving
                        kaartje.url = reverse(
                            'CompInschrijven:leden-ingeschreven',
                            kwargs={'deelcomp_pk': deelcomp.pk})
                        if comp.afstand == '18':
                            kaartje.img = static('plein/badge_nhb_indoor.png')
                        else:
                            kaartje.img = static('plein/badge_nhb_25m1p.png')
                        kaartjes.append(kaartje)

                    # 5 - wie schiet waar
                    if deelcomp.inschrijf_methode == INSCHRIJF_METHODE_1 and 'B' <= comp.fase <= 'F':
                        kaartje = SimpleNamespace()
                        kaartje.titel = "Wie schiet waar?"
                        kaartje.tekst = 'Overzicht gekozen wedstrijden voor de %s.' % comp.beschrijving
                        kaartje.url = reverse(
                            'CompRegio:wie-schiet-waar',
                            kwargs={'deelcomp_pk': deelcomp.pk})
                        kaartje.icon = 'gamepad'
                        if comp.fase < 'B':
                            kaartje.beschikbaar_vanaf = localize(
                                comp.begin_aanmeldingen)
                        kaartjes.append(kaartje)
            # for

        # for

        eval_open_taken(self.request)

        menu_dynamics(self.request, context, actief='vereniging')
        return context
示例#53
0
favicon_paths = [
    'apple-touch-icon-180x180.png', 'apple-touch-icon-114x114.png',
    'android-chrome-72x72.png', 'apple-touch-icon-57x57.png',
    'apple-touch-icon-72x72.png', 'apple-touch-icon.png', 'mstile-70x70.png',
    'android-chrome-36x36.png', 'apple-touch-icon-precomposed.png',
    'apple-touch-icon-76x76.png', 'apple-touch-icon-60x60.png',
    'android-chrome-96x96.png', 'mstile-144x144.png', 'mstile-150x150.png',
    'safari-pinned-tab.svg', 'android-chrome-144x144.png',
    'apple-touch-icon-152x152.png', 'favicon-96x96.png', 'favicon-32x32.png',
    'favicon-16x16.png', 'android-chrome-192x192.png',
    'android-chrome-48x48.png', 'mstile-310x150.png',
    'apple-touch-icon-144x144.png', 'browserconfig.xml', 'manifest.json',
    'apple-touch-icon-120x120.png', 'mstile-310x310.png'
]

for favicon in favicon_paths:
    urlpatterns.append(
        url(
            r'^%s$' % favicon,
            RedirectView.as_view(
                url=lazystr(lambda: static('icons/' + favicon)), )))

handler404 = 'judge.views.error.error404'
handler403 = 'judge.views.error.error403'
handler500 = 'judge.views.error.error500'

if 'newsletter' in settings.INSTALLED_APPS:
    urlpatterns.append(url(r'^newsletter/', include('newsletter.urls')))
if 'impersonate' in settings.INSTALLED_APPS:
    urlpatterns.append(url(r'^impersonate/', include('impersonate.urls')))
示例#54
0
 def avatar_url(self):
     if self.avatar and hasattr(self.avatar, 'url'):
         return self.avatar.url
     else:
         return static('img/default-avatar.jpg')
示例#55
0
# -*- coding: utf-8 -*-
#
from django.templatetags.static import static
from django.conf import settings
from django.utils.translation import ugettext_lazy as _

default_context = {
    'DEFAULT_PK': '00000000-0000-0000-0000-000000000000',
    'LOGO_URL': static('img/logo.png'),
    'LOGO_TEXT_URL': static('img/logo_text.png'),
    'LOGIN_IMAGE_URL': static('img/login_image.jpg'),
    'FAVICON_URL': static('img/facio.ico'),
    'LOGIN_CAS_LOGO_URL': static('img/login_cas_logo.png'),
    'LOGIN_WECOM_LOGO_URL': static('img/login_wecom_logo.png'),
    'LOGIN_DINGTALK_LOGO_URL': static('img/login_dingtalk_logo.png'),
    'LOGIN_FEISHU_LOGO_URL': static('img/login_feishu_logo.png'),
    'JMS_TITLE': _('JumpServer Open Source Bastion Host'),
}

default_interface = {
    'login_title': default_context['JMS_TITLE'],
    'logo_logout': default_context['LOGO_URL'],
    'logo_index': default_context['LOGO_TEXT_URL'],
    'login_image': default_context['LOGIN_IMAGE_URL'],
    'favicon': default_context['FAVICON_URL'],
}


def jumpserver_processor(request):
    # Setting default pk
    context = default_context
示例#56
0
def select_static_minified_file(cdn, files_dict):
    if cdn:
        file_url = files_dict[CDN_MIN]
    else:
        file_url = static(files_dict[COMMON_MIN])
    return '{}?{}'.format(file_url, STATIC_CONTENT_VERSION)
示例#57
0
 def get_photo_url(self):
     """Return the photo URL if set, otherwise a default image.
     """
     if self.photo:
         return self.photo.url
     return static('images/default_head.png')
示例#58
0
def evileg_core_cropper_min_js():
    return static("js/cropper.min.js")
示例#59
0
 def scripts(self):
     scripts = super().scripts
     scripts.append(static("debug_toolbar/js/history.js"))
     return scripts
示例#60
0
文件: models.py 项目: open-tribe/web
 def static_image(self):
     if 'v2' in self.image:
         return static(self.image)
     return self.image