def get_image_placeholder(context, name, **kwargs): default_image = kwargs.pop('default', DEFAULT_IMAGE) p, content = get_placeholder(context, name, **kwargs) try: image = Image.objects.get(pk=p.content) alternative_text = image.alternative_text image_path = image.file.path image_url = image.file.url except Exception: image = None alternative_text = '' image_path = '{}://{}{}'.format( 'https' if context['request'].is_secure() else 'http', get_current_site(context['request']).domain, staticfiles_storage.url(default_image)) image_url = staticfiles_storage.url(default_image) if 'geometry' in kwargs: # some kwargs are left, assuming in order to call sorl source = get_thumbnail( image_path, kwargs.pop('geometry', ''), **kwargs).url else: source = image_url return p, mark_safe('<img src="{}" alt="{}">'.format( source, alternative_text))
def javascript(filename, type='text/javascript'): '''A simple shortcut to render a ``script`` tag to a static javascript file''' if '?' in filename and len(filename.split('?')) is 2: filename, params = filename.split('?') return '<script type="%s" src="%s?%s"></script>' % (type, staticfiles_storage.url(filename), params) else: return '<script type="%s" src="%s"></script>' % (type, staticfiles_storage.url(filename))
def prop_media(self): return forms.Media(css={'all': (staticfiles_storage.url('css/jquery-ui-1.10.4.custom.css'),)}, js=( staticfiles_storage.url('js/jquery-1.10.2.js'), staticfiles_storage.url('js/jquery.form.js'), staticfiles_storage.url('js/jquery-ui-1.10.4.custom.js'), staticfiles_storage.url('js/calendar.js')))
def browserid_js(include_shim=True): """ Return <script> tags for the JavaScript required by the BrowserID login button. Requires use of the staticfiles app. If the BROWSERID_AUTOLOGIN_ENABLED setting is True, an extra JavaScript file for mocking out Persona will be included, and the shim won't be included regardless of the value of the ``include_shim`` setting. :param include_shim: A boolean that determines if the persona.org JavaScript shim is included in the output. Useful if you want to minify the button JavaScript using a library like django-compressor that can't handle external JavaScript. """ files = [] autologin_enabled = getattr(settings, "BROWSERID_AUTOLOGIN_ENABLED", False) # Include navigator.id shim only if we're not doing autologin. if include_shim and not autologin_enabled: files.append(getattr(settings, "BROWSERID_SHIM", "https://login.persona.org/include.js")) # Include django-browserid API files.append(staticfiles_storage.url("browserid/api.js")) # If we're doing autologin, include the JS to mock out certain parts # of the API. if autologin_enabled: files.append(staticfiles_storage.url("browserid/autologin.js")) # Include the JS to bind to login buttons. files.append(staticfiles_storage.url("browserid/browserid.js")) tags = ['<script type="text/javascript" src="{0}"></script>'.format(path) for path in files] return mark_safe("\n".join(tags))
def plan_tests(request, plan_id, editable=True): templates = get_handlebars_templates(settings.XGDS_PLANNER2_HANDLEBARS_DIRS, 'XGDS_PLANNER2_HANDLEBARS_DIRS') plan = PLAN_MODEL.get().objects.get(pk=plan_id) plan_json = plan.jsonPlan if not plan_json.serverId: plan_json.serverId = plan.pk if "None" in plan_json.url: plan_json.url = plan.get_absolute_url() planSchema = models.getPlanSchema(plan_json.platform.name) # print planSchema.getJsonSchema(); return render_to_response( 'xgds_planner2/planner_tests.html', RequestContext(request, { 'templates': templates, 'plan_schema_json': planSchema.getJsonSchema(), # xpjson.dumpDocumentToString(planSchema.getSchema()), 'plan_library_json': planSchema.getJsonLibrary(), # xpjson.dumpDocumentToString(planSchema.getLibrary()), 'plan_json': json.dumps(plan_json), 'plan_name': plan.name, 'plan_index_json': json.dumps(plan_index_json()), 'editable': editable, 'simulatorUrl': planSchema.simulatorUrl, 'simulator': planSchema.simulator, 'placemark_circle_url': request.build_absolute_uri( staticfiles_storage.url('xgds_planner2/images/placemark_circle.png') ), 'placemark_circle_highlighted_url': request.build_absolute_uri( staticfiles_storage.url('xgds_planner2/images/placemark_circle_highlighted.png') ), 'plan_links_json': json.dumps(plan.getLinks()), 'plan_namedURLs_json': json.dumps(plan.namedURLs), }), # context_instance=RequestContext )
def _build_standalone_tag(module): """ Generate a RequireJS script tag for a standalone module. If the config has a 'devel_tag' attribute set to 'separate_tag', generate a separate tag type. """ module_section = require_settings.REQUIRE_STANDALONE_MODULES[module] relative_baseurl = module_section.get('relative_baseurl', '') entry_file_name = _get_standalone_entry_filename(module, module_section) relative_path = os.path.join(relative_baseurl, entry_file_name) module_url = staticfiles_storage.url(resolve_require_module(relative_path)) if not require_settings.REQUIRE_DEBUG: # Production mode, output the compiled script tag result = ( '<script type="text/javascript" src="{0}">' '</script>').format(module_url) return mark_safe(result) # Development mode generation below devel_tag = module_section.get('devel_tag', 'data_attr') require_url = staticfiles_storage.url( resolve_require_url(require_settings.REQUIRE_JS)) if devel_tag == 'separate_tag': # Separate script tag mode result = ( '<script type="text/javascript" src="{0}"></script>' '<script type="text/javascript" src="{1}"></script>').format( require_url, module_url) return mark_safe(result) # Data attribute mode (devel_tag == 'data_attr') result = ( '<script type="text/javascript" src="{0}" data-main="{1}">' '</script>').format(require_url, module_url) return mark_safe(result)
def socketio_js(include_flash=True): script_path = staticfiles_storage.url('js/socket.io.js') swf_script = "" if include_flash: swf_path = staticfiles_storage.url('flashsocket/WebSocketMain.swf') swf_script = '<script type="text/javascript">WEB_SOCKET_SWF_LOCATION="%s";</script>' % ( swf_path ) return '<script type="text/javascript" src="%s"></script>\n%s' % ( script_path, swf_script )
def javascript(filename, type="text/javascript"): """A simple shortcut to render a ``script`` tag to a static javascript file""" if "?" in filename and len(filename.split("?")) is 2: filename, params = filename.split("?") return '<script type="%s" src="%s?%s"></script>' % (type, staticfiles_storage.url(filename), params) else: return '<script type="%s" src="%s"></script>' % (type, staticfiles_storage.url(filename))
def get_image_url(self): if self.twitter_profile_data and 'profile_image_url' in self.twitter_profile_data: return self.twitter_profile_data['profile_image_url'] elif self.facebook_profile_data: return '%s?type=square' % utils.graph_api_url('%s/picture' % self.username) elif self.foursquare_profile_data and 'photo' in self.foursquare_profile_data: return self.foursquare_profile_data['photo'] elif self.google_profile_data and 'picture' in self.google_profile_data: return self.google_profile_data['picture'] elif self.email: request = client.RequestFactory(**settings.DEFAULT_REQUEST).request() default_url = request.build_absolute_uri(staticfiles_storage.url(settings.DEFAULT_USER_IMAGE)) return 'https://secure.gravatar.com/avatar/%(email_hash)s?%(args)s' % { 'email_hash': hashlib.md5(self.email.lower()).hexdigest(), 'args': urllib.urlencode({ 'default': default_url, 'size': 50, }), } else: return staticfiles_storage.url(settings.DEFAULT_USER_IMAGE)
def _media(self): media = super(HeavyPreviewAdminPageDownWidget, self)._media() media.add_css({'all': [ staticfiles_storage.url('pygment-github.css'), staticfiles_storage.url('table.css'), ]}) return media
def __init__(self, *args, **kwargs): super(JEditableMixin, self).__init__(*args, **kwargs) _cls_names = [] for fld in self.fields: _form_field = self.fields[fld] if _form_field.widget.__class__.__name__ in ( 'BootstrapRadioSelect', 'RadioSelect'): _form_field.widget = forms.Select(choices=_form_field.choices) _cls_name = _form_field.__class__.__name__ if _cls_name not in _cls_names: _cls_names.append(_cls_name) if 'DateField' == _cls_name: _cls_names.append('datepicker') self.fields[fld].widget = forms.widgets.TextInput(attrs={'class': _cls_names, 'type':'date'}) if not _form_field.show_hidden_initial: attrs = _form_field.widget.attrs widget_attrs = self.generate_jeditable_attrs(fld) attrs.update(widget_attrs) #if 'DateField' == _cls_name: # attrs.update({'data-date':'2014-01-01'}) # add media as required if not getattr(self.Media, 'js', False): self.Media.js = () self.Media.css = {'screen': (),} if 'BooleanField' in _cls_names or 'NullBooleanField' in _cls_names: self.Media.js += (staticfiles_storage.url('common/js/jquery.icheck.min.js'),) self.Media.css['screen'] += (staticfiles_storage.url('common/css/icheck/skins/flat/blue.css'),) if 'ModelMultipleChoiceField' in _cls_names: self.Media.js += (staticfiles_storage.url('common/js/chosen.jquery.min.js'),) self.Media.css['screen'] += (staticfiles_storage.url('common/css/chosen.min.css'),) # prevent multiple media includes self.Media.js = tuple(set(self.Media.js)) self.Media.css['screen'] = tuple(set(self.Media.css['screen']))
def episode_status_icon(action): if not action or not action.action: s = '<img src="%s" alt="nothing" title="%s" />' % \ (staticfiles_storage.url('nothing.png'), _('Unplayed episode')) else: date_string = (_(' on %s') % (action.timestamp)) if action.timestamp else '' device_string = (_(' on %s') % (action.client.name)) if action.client else '' if action.action == 'flattr': s = '<img src="https://flattr.com/_img/icons/flattr_logo_16.png" alt="flattr" title="%s" />' % (_("The episode has been flattr'd"),) elif action.action == 'new': s = '<img src="%s" alt="new" title="%s" />' % (staticfiles_storage.url('new.png'), '%s%s%s' % (_('This episode has been marked new'),date_string, device_string)) elif action.action == 'download': s = '<img src="%s" alt="downloaded" title="%s" />' % (staticfiles_storage.url('download.png'), '%s%s%s' % (_('This episode has been downloaded'),date_string, device_string)) elif action.action == 'play': if action.stopped is not None: if getattr(action, 'started', None) is not None: playback_info = _(' from %(start)s to %(end)s') % { \ 'start': utils.format_time(action.started), \ 'end': utils.format_time(action.stopped)} else: playback_info = _(' to position %s') % (\ utils.format_time(action.stopped),) else: playback_info = '' s = '<img src="%s" alt="played" title="%s" />' % (staticfiles_storage.url('playback.png'), '%s%s%s%s' % (_('This episode has been played'),date_string, device_string, playback_info)) elif action.action == 'delete': s = '<img src="%s" alt="deleted" title="%s"/>' % (staticfiles_storage.url('delete.png'), '%s%s%s' % (_('This episode has been deleted'),date_string, device_string)) else: return action.action # this is not marked safe by intention return mark_safe(s)
def cache(self): ignore_patterns = getattr(settings, "STATICFILES_IGNORE_PATTERNS", None) if settings.PIPELINE_ENABLED: for package in self.packages: path = package.output_filename self.package_files.append(path) yield staticfiles_storage.url(path) else: for package in self.packages: for path in self.packager.compile(package.paths): self.package_files.append(path) yield staticfiles_storage.url(path) for finder in self.finders: for path, storage in finder.list(ignore_patterns): # Prefix the relative path if the source storage contains it if getattr(storage, 'prefix', None): prefixed_path = os.path.join(storage.prefix, path) else: prefixed_path = path # Dont add any doubles if prefixed_path not in self.package_files: self.package_files.append(prefixed_path) yield staticfiles_storage.url(prefixed_path)
def url_for(app, filename, site_slug=None): if app == 'static' and not site_slug: return staticfiles_storage.url(filename) elif app == 'static': return staticfiles_storage.url(site_slug + '/static/' + filename) else: raise ValueError("url_for doesn't know about %s" % app)
def add_edit_resources(context): """ Possibly inject Xtheme editor injection resources into the given context's resources. :param context: Jinja rendering context :type context: jinja2.runtime.Context """ request = context.get("request") if not can_edit(context): return try: command_url = reverse("shuup:xtheme") edit_url = reverse("shuup:xtheme_editor") inject_snipper = reverse("shuup_admin:xtheme_snippet.list") except NoReverseMatch: # No URLs no resources return from .rendering import get_view_config # avoid circular import view_config = get_view_config(context) theme = get_current_theme(request.shop) add_resource(context, "body_end", InlineScriptResource.from_vars("XthemeEditorConfig", { "commandUrl": command_url, "editUrl": edit_url, "injectSnipperUrl": inject_snipper, "themeIdentifier": theme.identifier, "viewName": view_config.view_name, "edit": is_edit_mode(request), "csrfToken": get_token(request), })) add_resource(context, "head_end", staticfiles_storage.url("xtheme/editor-injection.css")) add_resource(context, "body_end", staticfiles_storage.url("xtheme/editor-injection.js"))
def _media(self): media = super(AdminPagedownWidget, self)._media() media.add_css({'all': [ staticfiles_storage.url('content-description.css'), staticfiles_storage.url('admin/css/pagedown.css'), ]}) media.add_js([staticfiles_storage.url('admin/js/pagedown.js')]) return media
def _media(self): media = super(MathJaxPagedownWidget, self)._media() media.add_js([ staticfiles_storage.url('mathjax_config.js'), '//cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML', staticfiles_storage.url('pagedown_math.js'), ]) return media
def testRequireModule(self): with self.settings(REQUIRE_JS="require.js", REQUIRE_BASE_URL="js", REQUIRE_STANDALONE_MODULES={}): self.assertHTMLEqual( require_module("main"), """<script src="{}" data-main="{}"></script>""".format( staticfiles_storage.url("js/require.js"), staticfiles_storage.url("js/main.js") ), )
def replace_static_url(original, prefix, quote, rest): """ Replace a single matched url. """ original_uri = "".join([prefix, rest]) # Don't mess with things that end in '?raw' if rest.endswith('?raw'): static_paths_out.append((original_uri, original_uri)) return original # In debug mode, if we can find the url as is, if settings.DEBUG and finders.find(rest, True): static_paths_out.append((original_uri, original_uri)) return original # if we're running with a MongoBacked store course_namespace is not None, then use studio style urls elif (not static_asset_path) and course_id: # first look in the static file pipeline and see if we are trying to reference # a piece of static content which is in the edx-platform repo (e.g. JS associated with an xmodule) exists_in_staticfiles_storage = False try: exists_in_staticfiles_storage = staticfiles_storage.exists(rest) except Exception as err: log.warning("staticfiles_storage couldn't find path {0}: {1}".format( rest, str(err))) if exists_in_staticfiles_storage: url = staticfiles_storage.url(rest) else: # if not, then assume it's courseware specific content and then look in the # Mongo-backed database # Import is placed here to avoid model import at project startup. from static_replace.models import AssetBaseUrlConfig, AssetExcludedExtensionsConfig base_url = AssetBaseUrlConfig.get_base_url() excluded_exts = AssetExcludedExtensionsConfig.get_excluded_extensions() url = StaticContent.get_canonicalized_asset_path(course_id, rest, base_url, excluded_exts) if AssetLocator.CANONICAL_NAMESPACE in url: url = url.replace('block@', 'block/', 1) # Otherwise, look the file up in staticfiles_storage, and append the data directory if needed else: course_path = "/".join((static_asset_path or data_directory, rest)) try: if staticfiles_storage.exists(rest): url = staticfiles_storage.url(rest) else: url = staticfiles_storage.url(course_path) # And if that fails, assume that it's course content, and add manually data directory except Exception as err: log.warning("staticfiles_storage couldn't find path {0}: {1}".format( rest, str(err))) url = "".join([prefix, course_path]) static_paths_out.append((original_uri, url)) return "".join([quote, url, quote])
def podcast_status_icon(action): if action.action == 'subscribe': s = '<img src="%s" />' % (staticfiles_storage.url('subscribe.png'),) elif action.action == 'unsubscribe': s = '<img src="%s" />' % (staticfiles_storage.url('unsubscribe.png'),) elif action.action == 'flattr': s = '<img src="https://flattr.com/_img/icons/flattr_logo_16.png" />' return mark_safe(s)
def plan_editor_app(request, plan_id=None, editable=True): templates = get_handlebars_templates(settings.XGDS_PLANNER2_HANDLEBARS_DIRS, 'XGDS_PLANNER2_HANDLEBARS_DIRS') plan = PLAN_MODEL.get().objects.get(pk=plan_id) dirty = False if not plan.jsonPlan.serverId: plan.jsonPlan.serverId = plan.pk dirty = True if "None" in plan.jsonPlan.url: plan.jsonPlan.url = plan.get_absolute_url() dirty = True if dirty: plan.save() planSchema = models.getPlanSchema(plan.jsonPlan.platform.name) pe = None try: if plan.executions and plan.executions.count() > 0: pe = json.dumps(plan.executions.all()[0].toSimpleDict(), cls=DatetimeJsonEncoder) except: pass context = { 'templates': templates, 'app': 'xgds_planner2/js/plannerApp.js', 'saveSearchForm': MapSearchForm(), 'searchForms': getSearchForms(), 'flight_names': json.dumps(getAllFlightNames()), 'plan_schema_json': planSchema.getJsonSchema(), # xpjson.dumpDocumentToString(planSchema.getSchema()), 'plan_library_json': planSchema.getJsonLibrary(), # xpjson.dumpDocumentToString(planSchema.getLibrary()), 'plan_json': json.dumps(plan.jsonPlan), 'plan_name': plan.name, 'plan_execution': pe, 'plan_index_json': json.dumps(plan_index_json()), 'editable': editable and not plan.readOnly, 'simulatorUrl': planSchema.simulatorUrl, 'simulator': planSchema.simulator, 'placemark_circle_url': request.build_absolute_uri( staticfiles_storage.url('xgds_planner2/images/placemark_circle.png') ), 'placemark_circle_highlighted_url': request.build_absolute_uri( staticfiles_storage.url('xgds_planner2/images/placemark_circle_highlighted.png') ), 'placemark_directional_url': request.build_absolute_uri( staticfiles_storage.url('xgds_planner2/images/placemark_directional.png') ), 'placemark_selected_directional_url': request.build_absolute_uri( staticfiles_storage.url('xgds_planner2/images/placemark_directional_highlighted.png') ), 'plan_links_json': json.dumps(plan.getLinks()) } return render_to_response( 'xgds_planner2/planner_app.html', RequestContext(request, getClassByName(settings.XGDS_PLANNER2_EDITOR_CONTEXT_METHOD)(context)), )
def learner_profile_context(request, profile_username, user_is_staff): """Context for the learner profile page. Args: logged_in_user (object): Logged In user. profile_username (str): username of user whose profile is requested. user_is_staff (bool): Logged In user has staff access. build_absolute_uri_func (): Returns: dict Raises: ObjectDoesNotExist: the specified profile_username does not exist. """ profile_user = User.objects.get(username=profile_username) logged_in_user = request.user own_profile = (logged_in_user.username == profile_username) account_settings_data = get_account_settings(request, profile_username) preferences_data = get_user_preferences(profile_user, profile_username) context = { 'data': { 'profile_user_id': profile_user.id, 'default_public_account_fields': settings.ACCOUNT_VISIBILITY_CONFIGURATION['public_fields'], 'default_visibility': settings.ACCOUNT_VISIBILITY_CONFIGURATION['default_visibility'], 'accounts_api_url': reverse("accounts_api", kwargs={'username': profile_username}), 'preferences_api_url': reverse('preferences_api', kwargs={'username': profile_username}), 'preferences_data': preferences_data, 'account_settings_data': account_settings_data, 'profile_image_upload_url': reverse('profile_image_upload', kwargs={'username': profile_username}), 'profile_image_remove_url': reverse('profile_image_remove', kwargs={'username': profile_username}), 'profile_image_max_bytes': settings.PROFILE_IMAGE_MAX_BYTES, 'profile_image_min_bytes': settings.PROFILE_IMAGE_MIN_BYTES, 'account_settings_page_url': reverse('account_settings'), 'has_preferences_access': (logged_in_user.username == profile_username or user_is_staff), 'own_profile': own_profile, 'country_options': list(countries), 'find_courses_url': marketing_link('COURSES'), 'language_options': settings.ALL_LANGUAGES, 'badges_logo': staticfiles_storage.url('certificates/images/backpack-logo.png'), 'badges_icon': staticfiles_storage.url('certificates/images/ico-mozillaopenbadges.png'), 'backpack_ui_img': staticfiles_storage.url('certificates/images/backpack-ui.png'), 'platform_name': microsite.get_value('platform_name', settings.PLATFORM_NAME), }, 'disable_courseware_js': True, 'show_program_listing': ProgramsApiConfig.current().show_program_listing, } if badges_enabled(): context['data']['badges_api_url'] = reverse("badges_api:user_assertions", kwargs={'username': profile_username}) return context
def get_html(self, html): html.append('<select' + self.base_attributes + '>') for i in range(1, 6): html.append(' <option value="{}"{}>{}</option>'.format(i, ' selected' if i==self.rating else '', i)) html.append('</select>') html.append_js('$("#{}").barrating({{theme: "bootstrap-stars"{}}});'.format(self.id, ', readonly: true' if self.readonly else '')) html.add_resource(staticfiles_storage.url('shark/js/jquery.barrating.min.js'), 'js', 'star_rating', 'main') html.add_resource(staticfiles_storage.url('shark/css/rating-themes/bootstrap-stars.css'), 'css', 'star_rating', 'bootstrap')
def get_media(self): """Returns the media used by the widget.""" js = [ staticfiles_storage.url("cms/js/tinymce/tinymce.min.js"), staticfiles_storage.url("cms/js/jquery.cms.wysiwyg.js"), ] css = {} return forms.Media(js=js, css=css)
def format_diff(value): if value > 1: s = '<img src="%s" title="+%s">' % \ (staticfiles_storage.url('better.png'), value) elif value < -1: s = '<img src="%s" title="%s">' % \ (staticfiles_storage.url('worse.png'), value) else: s = '' return mark_safe(s)
def get_media(self): """Returns the media used by the widget.""" js = [ staticfiles_storage.url("cms/js/ckeditor/ckeditor.js"), staticfiles_storage.url("cms/js/ckeditor/adapters/jquery.js"), staticfiles_storage.url("cms/js/jquery.cms.wysiwyg.js"), ] css = {} return forms.Media(js=js, css=css)
def icon_url(self): mt = mimetypes.guess_type(self.file.path)[0] if mt: path = u'img/mimetypes/%s.png' % mt.replace('/', '-') if staticfiles_storage.exists(path): return staticfiles_storage.url(path) path = u'img/mimetypes/%s.png' % self.file.path.rsplit('.', 1)[-1] if staticfiles_storage.exists(path): return staticfiles_storage.url(path) return staticfiles_storage.url(u'img/mimetypes/unknown.png')
def replace_static_url(original, prefix, quote, rest): """ Replace a single matched url. """ # Don't mess with things that end in '?raw' if rest.endswith('?raw'): return original # In debug mode, if we can find the url as is, if settings.DEBUG and finders.find(rest, True): return original # if we're running with a MongoBacked store course_namespace is not None, then use studio style urls elif (not static_asset_path) \ and course_id \ and modulestore().get_modulestore_type(course_id) != ModuleStoreEnum.Type.xml: # first look in the static file pipeline and see if we are trying to reference # a piece of static content which is in the edx-platform repo (e.g. JS associated with an xmodule) exists_in_staticfiles_storage = False try: exists_in_staticfiles_storage = staticfiles_storage.exists(rest) except Exception as err: log.warning("staticfiles_storage couldn't find path {0}: {1}".format( rest, str(err))) if exists_in_staticfiles_storage: url = staticfiles_storage.url(rest) else: # if not, then assume it's courseware specific content and then look in the # Mongo-backed database url = StaticContent.convert_legacy_static_url_with_course_id(rest, course_id) if AssetLocator.CANONICAL_NAMESPACE in url: url = url.replace('block@', 'block/', 1) # Otherwise, look the file up in staticfiles_storage, and append the data directory if needed else: course_path = "/".join((static_asset_path or data_directory, rest)) try: if staticfiles_storage.exists(rest): url = staticfiles_storage.url(rest) else: url = staticfiles_storage.url(course_path) # And if that fails, assume that it's course content, and add manually data directory except Exception as err: log.warning("staticfiles_storage couldn't find path {0}: {1}".format( rest, str(err))) url = "".join([prefix, course_path]) return "".join([quote, url, quote])
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(staticfiles_storage.url(vendor_js_file), "application/javascript", "head") for css_file in self.css_dependencies(): fragment.add_css_url(staticfiles_storage.url(css_file)) # Body dependencies for js_file in self.js_dependencies(): fragment.add_javascript_url(staticfiles_storage.url(js_file))
def add_fragment_resource_urls(self, fragment): """ Adds URLs for JS and CSS resources needed by this fragment. """ # Head dependencies for vendor_js_file in self.vendor_js_dependencies(): fragment.add_resource_url(staticfiles_storage.url(vendor_js_file), 'application/javascript', 'head') for css_file in self.css_dependencies(): fragment.add_css_url(staticfiles_storage.url(css_file)) # Body dependencies for js_file in self.js_dependencies(): fragment.add_javascript_url(staticfiles_storage.url(js_file))
def image(self): return staticfiles_storage.url('images/cats/sequence_labeling.jpg')
admin.site.site_header = "Tech MUD Admin" admin.site.site_title = "Tech MUD Admin Panel" urlpatterns = [ path('admin/', admin.site.urls), path('', views.Index, name='Index'), path('about/', views.About, name='About'), path('contact/', app_views.Contact, name='Contact'), path('accounts/', include('accounts.urls')), path('videos/', include('videos.urls')), path('blogs/', include('blog.urls')), path('projects/', include('projects.urls')), path('courses/', include('courses.urls')), path("ads.txt/", RedirectView.as_view(url=staticfiles_storage.url("ads.txt"))), # Facebook Link path('https://www.facebook.com/techmub/', views.Facebook, name="Facebook_link"), # Github Link path('https://github.com/mudasiralinizamani', views.Github, name="Github_link"), # Twiter Link path('https://twitter.com/Mudasir78169406', views.Twitter, name="Twitter_link"),
def _footer_static_url(request, name): """Construct an absolute URL to a static asset. """ return request.build_absolute_uri(staticfiles_storage.url(name))
def image(self): return staticfiles_storage.url('images/cats/seq2seq.jpg')
def css(filename): '''A simple shortcut to render a ``link`` tag to a static CSS file''' return mark_safe('<link rel="stylesheet" type="text/css" href="%s" />' % staticfiles_storage.url(filename))
from django.conf import settings from django.conf.urls import include, url from django.conf.urls.static import static from django.contrib import admin from django.contrib.staticfiles.storage import staticfiles_storage from django.views.generic.base import RedirectView urlpatterns = [ url(r"^admin/", admin.site.urls), url( r"^favicon.ico$", RedirectView.as_view( # the redirecting function url=staticfiles_storage.url( "aileen/images/aileen.ico" ) # converts the static directory + our favicon into a URL ), name="favicon", ), url(r"^", include("data.urls", namespace="data")), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) if settings.AILEEN_MODE in ("server", "both"): urlpatterns.append(url(r"^", include("server.urls", namespace="server"))) elif settings.AILEEN_MODE == "box": urlpatterns.extend(( url(r"^", include("box.urls", namespace="box")), url(r"^", include("calibration.urls", namespace="calibration")), ))
def learner_profile_context(request, profile_username, user_is_staff): """Context for the learner profile page. Args: logged_in_user (object): Logged In user. profile_username (str): username of user whose profile is requested. user_is_staff (bool): Logged In user has staff access. build_absolute_uri_func (): Returns: dict Raises: ObjectDoesNotExist: the specified profile_username does not exist. """ profile_user = User.objects.get(username=profile_username) logged_in_user = request.user own_profile = (logged_in_user.username == profile_username) account_settings_data = get_account_settings(request, [profile_username])[0] preferences_data = get_user_preferences(profile_user, profile_username) context = { 'own_profile': own_profile, 'platform_name': configuration_helpers.get_value('platform_name', settings.PLATFORM_NAME), 'data': { 'profile_user_id': profile_user.id, 'default_public_account_fields': settings.ACCOUNT_VISIBILITY_CONFIGURATION['public_fields'], 'default_visibility': settings.ACCOUNT_VISIBILITY_CONFIGURATION['default_visibility'], 'accounts_api_url': reverse("accounts_api", kwargs={'username': profile_username}), 'preferences_api_url': reverse('preferences_api', kwargs={'username': profile_username}), 'preferences_data': preferences_data, 'account_settings_data': account_settings_data, 'profile_image_upload_url': reverse('profile_image_upload', kwargs={'username': profile_username}), 'profile_image_remove_url': reverse('profile_image_remove', kwargs={'username': profile_username}), 'profile_image_max_bytes': settings.PROFILE_IMAGE_MAX_BYTES, 'profile_image_min_bytes': settings.PROFILE_IMAGE_MIN_BYTES, 'account_settings_page_url': reverse('account_settings'), 'has_preferences_access': (logged_in_user.username == profile_username or user_is_staff), 'own_profile': own_profile, 'country_options': list(countries), 'find_courses_url': marketing_link('COURSES'), 'language_options': settings.ALL_LANGUAGES, 'badges_logo': staticfiles_storage.url('certificates/images/backpack-logo.png'), 'badges_icon': staticfiles_storage.url( 'certificates/images/ico-mozillaopenbadges.png'), 'backpack_ui_img': staticfiles_storage.url('certificates/images/backpack-ui.png'), 'platform_name': configuration_helpers.get_value('platform_name', settings.PLATFORM_NAME), 'social_platforms': settings.SOCIAL_PLATFORMS, }, 'show_program_listing': ProgramsApiConfig.is_enabled(), 'show_dashboard_tabs': True, 'disable_courseware_js': True, 'nav_hidden': True, 'records_url': get_credentials_records_url(), } if own_profile or user_is_staff: achievements_fragment = LearnerAchievementsFragmentView( ).render_to_fragment( request, username=profile_user.username, own_profile=own_profile, ) context['achievements_fragment'] = achievements_fragment if badges_enabled(): context['data']['badges_api_url'] = reverse( "badges_api:user_assertions", kwargs={'username': profile_username}) return context
def __init__(self, src): self._data = src self.url = staticfiles_storage.url(src)
def episode_status_icon(action): if not action or not action.action: s = '<img src="%s" alt="nothing" title="%s" />' % ( staticfiles_storage.url('nothing.png'), _('Unplayed episode'), ) else: date_string = (_(' on %s') % (action.timestamp)) if action.timestamp else '' device_string = (_(' on %s') % (action.client.name)) if action.client else '' if action.action == 'flattr': s = ( '<img src="https://flattr.com/_img/icons/flattr_logo_16.png" alt="flattr" title="%s" />' % (_("The episode has been flattr'd"), )) elif action.action == 'new': s = '<img src="%s" alt="new" title="%s" />' % ( staticfiles_storage.url('new.png'), '%s%s%s' % (_('This episode has been marked new'), date_string, device_string), ) elif action.action == 'download': s = '<img src="%s" alt="downloaded" title="%s" />' % ( staticfiles_storage.url('download.png'), '%s%s%s' % (_('This episode has been downloaded'), date_string, device_string), ) elif action.action == 'play': if action.stopped is not None: if getattr(action, 'started', None) is not None: playback_info = _(' from %(start)s to %(end)s') % { 'start': utils.format_time(action.started), 'end': utils.format_time(action.stopped), } else: playback_info = _(' to position %s') % (utils.format_time( action.stopped), ) else: playback_info = '' s = '<img src="%s" alt="played" title="%s" />' % ( staticfiles_storage.url('playback.png'), '%s%s%s%s' % ( _('This episode has been played'), date_string, device_string, playback_info, ), ) elif action.action == 'delete': s = '<img src="%s" alt="deleted" title="%s"/>' % ( staticfiles_storage.url('delete.png'), '%s%s%s' % (_('This episode has been deleted'), date_string, device_string), ) else: return action.action # this is not marked safe by intention return mark_safe(s)
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.staticfiles.storage import staticfiles_storage from django.views.generic.base import RedirectView from django.conf.urls.static import static from django.urls import path, include from django.contrib import admin from django.conf import settings from django.urls import reverse urlpatterns = [ path('admin/', admin.site.urls), path( 'favicon.ico', RedirectView.as_view( url=staticfiles_storage.url('images/favicon.ico'))), path('', RedirectView.as_view(url='chats/list/')), path('', include('apps.users.urls')), path('api/', include('api.api_urls')), path('chats/', include('apps.chats.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
def _static(self, path): return staticfiles_storage.url(path)
def _get_default_video_image_url(): """ Returns default video image url """ return staticfiles_storage.url(settings.VIDEO_IMAGE_DEFAULT_FILENAME)
def image(self): return staticfiles_storage.url('images/cats/text_classification.jpg')
from django.urls import path from django.contrib.staticfiles.storage import staticfiles_storage from django.views.generic.base import RedirectView from . import views urlpatterns = [ path('', views.index, name='index'), path('favicon.ico/', RedirectView.as_view( url=staticfiles_storage.url('puffer/dist/images/favicon.ico')), name='favicon'), path('player/', views.player, name='player'), path('faq/', views.faq, name='faq'), path('terms/', views.terms, name='terms'), path('data/', views.data, name='data'), path('error_reporting/', views.error_reporting, name='error_reporting'), ]
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 . import views from django.conf.urls.static import static from django.views.generic.base import TemplateView from django.contrib.auth import views as auth_views from django.views.generic.base import RedirectView from django.conf.urls.i18n import i18n_patterns from django.contrib.staticfiles.storage import staticfiles_storage from django.conf import settings urlpatterns = i18n_patterns( #path("admin/", admin.site.urls), path("", include("grouping_serv.apps.public.urls")), path("accounts/", include("grouping_serv.apps.accounts.urls")), path( 'favicon.ico', RedirectView.as_view( url=staticfiles_storage.url('logos/favicon.ico'))), path('i18n/', include('django.conf.urls.i18n'), name='i18n')) + static( settings.STATIC_URL, document_root=settings.STATIC_ROOT)
'MODERNIZR_STORAGE': 'cookie', 'MODERNIZR_COOKIE_NAME': 'modernizr', 'MODERNIZR_COOKIE_AGE': 60 * 60 * 24 * 7 * 2, # 2 weeks 'MODERNIZR_COOKIE_DOMAIN': None, 'MODERNIZR_COOKIE_SECURE': False, 'MODERNIZR_COOKIE_PATH': '/', 'MODERNIZR_SESSION_KEY': 'modernizr', 'MODERNIZR_JS_URL': staticfiles_storage.url('js/modernizr-custom.js'), 'MODERNIZR_SENTINEL_IMAGE_URL': staticfiles_storage.url('images/1.js'), 'MODERNIZR_INCLUDE_TAG': 'body', }) _HTML_TYPES = ('text/html', 'application/xhtml+xml') def replace_insensitive(string, target, replacement): """ Similar to string.replace() but is case insensitive Code borrowed from: http://forums.devshed.com/python-programming-11/case-insensitive-string-replace-490921.html """ no_case = string.lower()
def render_to_fragment( self, request, course_id=None, discussion_id=None, thread_id=None, profile_page_context=None, **kwargs ): """ Render the discussion board to a fragment. Args: request: The Django request. course_id: The id of the course in question. discussion_id: An optional discussion ID to be focused upon. thread_id: An optional ID of the thread to be shown. Returns: Fragment: The fragment representing the discussion board """ try: course_key = CourseKey.from_string(course_id) base_context = _create_base_discussion_view_context(request, course_key) # Note: # After the thread is rendered in this fragment, an AJAX # request is made and the thread is completely loaded again # (yes, this is something to fix). Because of this, we pass in # raise_event=False to _load_thread_for_viewing avoid duplicate # tracking events. thread = ( _load_thread_for_viewing( request, base_context['course'], discussion_id=discussion_id, thread_id=thread_id, raise_event=False, ) if thread_id else None ) context = _create_discussion_board_context(request, base_context, thread=thread) course_expiration_fragment = generate_course_expired_fragment(request.user, context['course']) context.update({ 'course_expiration_fragment': course_expiration_fragment, }) if profile_page_context: # EDUCATOR-2119: styles are hard to reconcile if the profile page isn't also a fragment html = render_to_string('discussion/discussion_profile_page.html', profile_page_context) else: html = render_to_string('discussion/discussion_board_fragment.html', context) fragment = Fragment(html) self.add_fragment_resource_urls(fragment) inline_js = render_to_string('discussion/discussion_board_js.template', context) fragment.add_javascript(inline_js) if not settings.REQUIRE_DEBUG: fragment.add_javascript_url(staticfiles_storage.url('discussion/js/discussion_board_factory.js')) return fragment except cc.utils.CommentClientMaintenanceError: log.warning('Forum is in maintenance mode') html = render_to_string('discussion/maintenance_fragment.html', { 'disable_courseware_js': True, 'uses_bootstrap': True, }) fragment = Fragment(html) self.add_fragment_resource_urls(fragment) return fragment except TeamDiscussionHiddenFromUserException: log.warning( u'User with id={user_id} tried to view private discussion with id={discussion_id}'.format( user_id=request.user.id, discussion_id=discussion_id ) ) html = render_to_string('discussion/discussion_private_fragment.html', { 'disable_courseware_js': True, 'uses_bootstrap': True, }) fragment = Fragment(html) self.add_fragment_resource_urls(fragment) return fragment
def url_for(app, filename): if app == 'static': return staticfiles_storage.url(filename) else: raise ValueError("url_for doesn't know about %s" % app)
def get_static_url(self, name): try: return staticfiles_storage.url(name) except ValueError: return None
def get_static_url(self, name): try: return decode_if_byte_string(staticfiles_storage.url(name)) except ValueError: return None
def conditional_js(context, script_name): suffix = '' if context.get('DEBUG', True) else '.min' filename = 'js/{}{}.js'.format(script_name, suffix) url = staticfiles_storage.url(filename) tag = '<script src="{}"></script>'.format(url) return mark_safe(tag)
import app.forms import app.views from django.contrib.staticfiles.storage import staticfiles_storage from django.views.generic.base import RedirectView # Uncomment the next lines to enable the admin: from django.conf.urls import include from django.contrib import admin #from app.forms import AutoCompleteView # admin.autodiscover() urlpatterns = [ # Examples: url(r'^favicon.ico$', RedirectView.as_view( url=staticfiles_storage.url('app/images/favicon.ico'), permanent=False), name="favicon"), url(r'^api/get_parts/', app.views.get_parts, name='get_parts'), url(r'^api/get_customers/', app.views.get_customers, name='get_customers'), url(r'^$', app.views.home, name='home'), url(r'^startInvoice$', app.views.startInvoice, name='startInvoice'), url(r'^updateInvoice/(?P<pk>\d+)$', app.views.updateInvoice, name='updateInvoice'), url(r'^invoice/(?P<pk>\d+)$', app.views.invoice, name='invoice'), url(r'^CustomerBills/(?P<customerID>\d+)$', app.views.customerBills, name='customerBills'), url(r'^TotalBills$', app.views.totalBills, name='totalBills'), url(r'^PaidBills$', app.views.paidBills, name='paidBills'),
def logo_url(self): return staticfiles_storage.url(self.logo_filename)
def icon(self): apps = appmanager.get_apps_dict() try: if self.extra == 'workflow2': return staticfiles_storage.url('oozie/art/icon_oozie_workflow_48.png') elif self.extra == 'coordinator2': return staticfiles_storage.url('oozie/art/icon_oozie_coordinator_48.png') elif self.extra == 'bundle2': return staticfiles_storage.url('oozie/art/icon_oozie_bundle_48.png') elif self.extra == 'notebook': return staticfiles_storage.url('notebook/art/icon_notebook_48.png') elif self.extra.startswith('query'): if self.extra == 'query-impala': return staticfiles_storage.url(apps['impala'].icon_path) else: return staticfiles_storage.url(apps['beeswax'].icon_path) elif self.extra.startswith('search'): return staticfiles_storage.url('search/art/icon_search_48.png') elif self.content_type.app_label == 'beeswax': if self.extra == '0': return staticfiles_storage.url(apps['beeswax'].icon_path) elif self.extra == '3': return staticfiles_storage.url(apps['spark'].icon_path) else: return staticfiles_storage.url(apps['impala'].icon_path) elif self.content_type.app_label == 'oozie': if self.extra == 'jobsub': return staticfiles_storage.url(apps['jobsub'].icon_path) else: return staticfiles_storage.url(self.content_type.model_class().ICON) elif self.content_type.app_label in apps: return staticfiles_storage.url(apps[self.content_type.app_label].icon_path) else: return staticfiles_storage.url('desktop/art/icon_hue_48.png') except Exception, e: LOG.warn(force_unicode(e)) return staticfiles_storage.url('desktop/art/icon_hue_48.png')
def get_static_url(cls, path): return super(StaticExtension, cls).get_static_url(staticfiles_storage.url(path))
def handle_simple(cls, path): if apps.is_installed('django.contrib.static'): from django.contrib.staticfiles.storage import staticfiles_storage return staticfiles_storage.url(path) else: return urljoin(PrefixNode.handle_simple("STATIC_URL"), quote(path))
from django.conf import settings from django.conf.urls import include, url from django.conf.urls.static import static from django.contrib import admin from django.contrib.staticfiles.storage import staticfiles_storage from django.urls import path from django.views.generic import RedirectView urlpatterns = [ url(r'^', include('apps.user_registration.urls')), url(r'^', include('apps.pages.urls')), url(r'^', include('apps.file_upload.urls')), url(r'^admin/', admin.site.urls), path('favicon.ico', RedirectView.as_view(url=staticfiles_storage.url('img/favicon.ico'))), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
from zerver.lib.realm_icon import get_realm_icon_url from zerver.lib.request import get_request_notes from zerver.lib.send_email import FromAddress from zerver.lib.subdomains import get_subdomain from zerver.models import Realm, UserProfile, get_realm from zproject.backends import ( AUTH_BACKEND_NAME_MAP, auth_enabled_helper, get_external_method_dicts, password_auth_enabled, require_email_format_usernames, ) DEFAULT_PAGE_PARAMS = { "development_environment": settings.DEVELOPMENT, "webpack_public_path": staticfiles_storage.url(settings.WEBPACK_BUNDLES), } def common_context(user: UserProfile) -> Dict[str, Any]: """Common context used for things like outgoing emails that don't have a request. """ return { "realm_uri": user.realm.uri, "realm_name": user.realm.name, "root_domain_uri": settings.ROOT_DOMAIN_URI, "external_uri_scheme": settings.EXTERNAL_URI_SCHEME, "external_host": settings.EXTERNAL_HOST, "user_name": user.full_name, }
def static(path): return staticfiles_storage.url(path)
def testStandaloneRequireModule(self): self.assertHTMLEqual( require_module("main"), """<script src="{0}"></script>""".format( staticfiles_storage.url("js/main-built.js"), ))