signature
stringlengths
8
3.44k
body
stringlengths
0
1.41M
docstring
stringlengths
1
122k
id
stringlengths
5
17
def pre_etl(self):
self.start_time = timezone.now()<EOL>return<EOL>
Prepare for ETL, for example, by prefetching other necessary data. By default, sets self.start_time. :return:
f4387:c0:m2
def transform(self, extracted_instance):
<EOL>return extracted_instance.__dict__<EOL>
Transform the extracted instance to a dictionary of **kwargs. :param extracted_instance: a record from the origin :return: A dict of kwargs to pass to load()
f4387:c0:m3
def load(self, **kwargs):
raise NotImplementedError<EOL>
:param kwargs: kwargs generated by transform() :return:
f4387:c0:m4
def origin_data(self):
return self.origin_qs.all()<EOL>
:return: An iterable of the datasource that is being extracted
f4387:c1:m0
def __unicode__(self):
levels = (x for x in (self.neighborhood, self.city, self.state_province, unicode(self.country)) if x)<EOL>r = "<STR_LIT:U+002CU+0020>".join (levels)<EOL>if self.colloquial_historical:<EOL><INDENT>if r:<EOL><INDENT>r = "<STR_LIT>".format(self.colloquial_historical, r)<EOL><DEDENT>else:<EOL><INDENT>r = self.colloquial_hi...
:return:
f4388:c1:m0
def get_layout_template_name(self):
if self.layout:<EOL><INDENT>return self.layout.template_name<EOL><DEDENT>return self.fallback_template<EOL>
Return ``layout.template_name`` or `fallback_template``.
f4389:c0:m0
def add_missing_placeholders(self):
content_type = ContentType.objects.get_for_model(self)<EOL>result = False<EOL>if self.layout:<EOL><INDENT>for data in self.layout.get_placeholder_data():<EOL><INDENT>placeholder, created = Placeholder.objects.update_or_create(<EOL>parent_type=content_type,<EOL>parent_id=self.pk,<EOL>slot=data.slot,<EOL>defaults=dict(<E...
Add missing placeholders from templates. Return `True` if any missing placeholders were created.
f4389:c0:m1
def __getattr__(self, item):
if item == '<STR_LIT>':<EOL><INDENT>return self.__get_list_image<EOL><DEDENT>super_type = super(ListableMixin, self)<EOL>if hasattr(super_type, '<STR_LIT>'):<EOL><INDENT>return super_type.__getattr__(item)<EOL><DEDENT>else:<EOL><INDENT>return self.__getattribute__(item)<EOL><DEDENT>
Only called if no class in the MRO defines the function
f4389:c3:m0
def __get_list_image(self):
list_image = first_of(<EOL>self,<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT:image>',<EOL>)<EOL>return getattr(list_image, "<STR_LIT:image>", list_image)<EOL>
:return: the ImageField to use for thumbnails in lists NB note that the Image Field is returned, not the ICEkit Image model as with get_hero_image (since the override is just a field and we don't need alt text), not Image record.
f4389:c3:m1
def get_type(self):
return type(self)._meta.verbose_name<EOL>
:return: a string OR object (with a get_absolute_url) indicating the public type of this object
f4389:c3:m2
def get_type_plural(self):
t = self.get_type()<EOL>if t:<EOL><INDENT>if hasattr(t, '<STR_LIT>'):<EOL><INDENT>return t.get_plural()<EOL><DEDENT>if t == type(self)._meta.verbose_name:<EOL><INDENT>return unicode(type(self)._meta.verbose_name_plural)<EOL><DEDENT>return u"<STR_LIT>".format(t)<EOL><DEDENT>return unicode(type(self)._meta.verbose_name_p...
:return: a string (event if get_type is an object) indicating the plural of the type name
f4389:c3:m3
def get_og_title(self):
if hasattr(self, '<STR_LIT>') and self.meta_title:<EOL><INDENT>return self.meta_title<EOL><DEDENT>return self.get_title()<EOL>
return meta_title if exists otherwise fall back to title
f4389:c3:m7
def get_og_image_url(self):
li = self.get_list_image()<EOL>if li:<EOL><INDENT>from easy_thumbnails.files import get_thumbnailer<EOL>thumb_url = get_thumbnailer(li)['<STR_LIT>'].url<EOL>return urljoin(settings.SITE_DOMAIN, thumb_url)<EOL><DEDENT>
:return: URL of the image to use in OG shares
f4389:c3:m8
def get_hero_image(self):
return self.hero_image<EOL>
Return the Image record to use as the Hero
f4389:c4:m0
def render_map(self):
return (<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>).format(<EOL>container_id=self.get_map_element_id(),<EOL>data=json.dumps(self.get_map_data()),<EOL>)<EOL>
Renders a container and JSON that is picked up by `static/icekit/js/google_map.js` which mounts a responsive static map with overlays and links
f4389:c5:m1
def get_map_data(self):
return {<EOL>'<STR_LIT>': '<STR_LIT:#>' + self.get_map_element_id(),<EOL>'<STR_LIT>': self.map_center_description,<EOL>'<STR_LIT>': self.map_marker_description or self.map_center_description,<EOL>'<STR_LIT>': self.map_zoom,<EOL>'<STR_LIT>': self.get_map_href(),<EOL>'<STR_LIT:key>': getattr(settings, '<STR_LIT>', '<STR_...
Returns a serializable data set describing the map location
f4389:c5:m2
def get_map_href(self):
if self.map_center_lat and self.map_center_long:<EOL><INDENT>params = {<EOL>'<STR_LIT>': '<STR_LIT>' % (self.map_center_lat, self.map_center_long)<EOL>}<EOL><DEDENT>else:<EOL><INDENT>params = {'<STR_LIT:q>': self.map_center_description}<EOL><DEDENT>return self.GOOGLE_MAPS_HREF_ROOT + urllib.urlencode(params)<EOL>
Returns a link to an external view of the map
f4389:c5:m3
def get_map_element_id(self):
return '<STR_LIT>' + str(id(self))<EOL>
Returns a unique identifier for a map element
f4389:c5:m4
def _get_ctypes(self):
ctypes = []<EOL>for related_object in self.model._meta.get_all_related_objects():<EOL><INDENT>model = getattr(related_object, '<STR_LIT>', related_object.model)<EOL>ctypes.append(ContentType.objects.get_for_model(model).pk)<EOL>if model.__subclasses__():<EOL><INDENT>for child in model.__subclasses__():<EOL><INDENT>ctyp...
Returns all related objects for this model.
f4391:c0:m0
def placeholder_data_view(self, request, id):
<EOL>try:<EOL><INDENT>layout = models.Layout.objects.get(pk=id)<EOL><DEDENT>except models.Layout.DoesNotExist:<EOL><INDENT>json = {'<STR_LIT:success>': False, '<STR_LIT:error>': '<STR_LIT>'}<EOL>status = <NUM_LIT><EOL><DEDENT>else:<EOL><INDENT>placeholders = layout.get_placeholder_data()<EOL>status = <NUM_LIT:200><EOL>...
Return placeholder data for the given layout's template.
f4391:c0:m3
def get_urls(self):
<EOL>urls = super(LayoutAdmin, self).get_urls()<EOL>my_urls = patterns(<EOL>'<STR_LIT>',<EOL>url(<EOL>r'<STR_LIT>',<EOL>self.admin_site.admin_view(self.placeholder_data_view),<EOL>name='<STR_LIT>',<EOL>)<EOL>)<EOL>return my_urls + urls<EOL>
Add ``layout_placeholder_data`` URL.
f4391:c0:m4
def clean(self):
data = super(PublishingAdminForm, self).clean()<EOL>cleaned_data = self.cleaned_data<EOL>instance = self.instance<EOL>unique_fields_set = instance.get_unique_together()<EOL>if not unique_fields_set:<EOL><INDENT>return data<EOL><DEDENT>for unique_fields in unique_fields_set:<EOL><INDENT>unique_filter = {}<EOL>for unique...
Additional clean data checks for path and keys. These are not cleaned in their respective methods e.g. `clean_slug` as they depend upon other field data. :return: Cleaned data.
f4392:c2:m1
def has_publish_permission(self, request, obj=None):
<EOL>if is_automatic_publishing_enabled(self.model):<EOL><INDENT>return False<EOL><DEDENT>user_obj = request.user<EOL>if not user_obj.is_active:<EOL><INDENT>return False<EOL><DEDENT>if user_obj.is_superuser:<EOL><INDENT>return True<EOL><DEDENT>if user_obj.has_perm('<STR_LIT>' % self.opts.app_label):<EOL><INDENT>return ...
Determines if the user has permissions to publish. :param request: Django request object. :param obj: The object to determine if the user has permissions to publish. :return: Boolean.
f4392:c3:m6
def has_preview_permission(self, request, obj=None):
<EOL>if self.has_publish_permission(request, obj=obj):<EOL><INDENT>return True<EOL><DEDENT>user_obj = request.user<EOL>if not user_obj.is_active:<EOL><INDENT>return False<EOL><DEDENT>if user_obj.is_staff:<EOL><INDENT>return True<EOL><DEDENT>return False<EOL>
Return `True` if the user has permissions to preview a publishable item. NOTE: this method does not actually change who can or cannot preview any particular item, just whether to show the preview link. The real dcision is made by a combination of: - `PublishingMiddleware` which chooses who can view draft content - th...
f4392:c3:m7
def publishing_column(self, obj):
<EOL>if hasattr(obj, '<STR_LIT>'):<EOL><INDENT>obj = obj.get_real_instance()<EOL><DEDENT>try:<EOL><INDENT>object_url = obj.get_absolute_url()<EOL><DEDENT>except (NoReverseMatch, AttributeError):<EOL><INDENT>object_url = '<STR_LIT>'<EOL><DEDENT>template_name = '<STR_LIT>'<EOL>t = loader.get_template(template_name)<EOL>c...
Render publishing-related status icons and view links for display in the admin.
f4392:c3:m8
def publish(self, request, qs):
<EOL>try:<EOL><INDENT>qs = self.model.objects.get_real_instances(qs)<EOL><DEDENT>except AttributeError:<EOL><INDENT>pass<EOL><DEDENT>for q in qs:<EOL><INDENT>if self.has_publish_permission(request, q):<EOL><INDENT>q.publish()<EOL><DEDENT><DEDENT>
Publish bulk action
f4392:c3:m9
def unpublish(self, request, qs):
<EOL>try:<EOL><INDENT>qs = self.model.objects.get_real_instances(qs)<EOL><DEDENT>except AttributeError:<EOL><INDENT>pass<EOL><DEDENT>for q in qs:<EOL><INDENT>q.unpublish()<EOL><DEDENT>
Unpublish bulk action
f4392:c3:m10
def find_first_available_template(self, template_name_list):
if isinstance(template_name_list, six.string_types):<EOL><INDENT>return template_name_list<EOL><DEDENT>else:<EOL><INDENT>return _select_template_name(template_name_list)<EOL><DEDENT>
Given a list of template names, find the first one that actually exists and is available.
f4392:c4:m1
def publishing_admin_filter_for_drafts(self, qs):
return qs.filter(publishing_is_draft=True)<EOL>
Remove published items from the given QS
f4392:c4:m3
def get_queryset(self, request):
<EOL>self.request = request<EOL>qs = self.model.objects<EOL>try:<EOL><INDENT>qs_language = self.get_queryset_language(request)<EOL>if qs_language:<EOL><INDENT>qs = qs.language(qs_language)<EOL><DEDENT><DEDENT>except AttributeError: <EOL><INDENT>pass<EOL><DEDENT>qs = self.publishing_admin_filter_for_drafts(qs)<EOL>orde...
The queryset to use for the administration list page. :param request: Django request object. :return: QuerySet.
f4392:c4:m4
def save_related(self, request, form, *args, **kwargs):
result = super(PublishingAdmin, self).save_related(request, form, *args, **kwargs)<EOL>if form.instance:<EOL><INDENT>publishing_signals.publishing_post_save_related.send(<EOL>sender=type(self), instance=form.instance)<EOL><DEDENT>return result<EOL>
Send the signal `publishing_post_save_related` when a draft copy is saved and all its relationships have also been created.
f4392:c4:m10
def render_change_form(self, request, context, add=False, change=False,<EOL>form_url='<STR_LIT>', obj=None):
obj = context.get('<STR_LIT>', None)<EOL>if obj:<EOL><INDENT>context['<STR_LIT:object>'] = obj<EOL>context['<STR_LIT>'] = obj.has_been_published<EOL>context['<STR_LIT>'] = obj.is_dirty<EOL>context['<STR_LIT>'] =self.has_preview_permission(request, obj)<EOL>if not self.has_publish_permission(request, obj):<EOL><INDENT>c...
Provides the context and rendering for the admin change form. :param request: Django request object. :param context: The context dictionary to be passed to the template. :param add: Should the add form be rendered? Boolean input. :param change: Should the change for be rendered? Boolean input. :param form_url: The URL...
f4392:c4:m11
def get_queryset(self, request):
self.request = request<EOL>qs = super(PublishingFluentPagesParentAdminMixin, self).get_queryset(request)<EOL>qs = qs.filter(status=UrlNode.DRAFT)<EOL>return qs<EOL>
Show only DRAFT Fluent page items in admin. NOTE: We rely on the `UrlNode.status` to recognise DRAFT versus PUBLISHED objects, since there the top-level `UrlNode` model and queryset don't know about ICEKit publishing.
f4392:c5:m0
@register.filter<EOL>def get_draft_url(url):
return utils.get_draft_url(url)<EOL>
Return the given URL with a draft mode HMAC in its querystring.
f4394:m0
def get_proxy_ancestor_classes(klass):
proxy_ancestor_classes = set()<EOL>for superclass in klass.__bases__:<EOL><INDENT>if hasattr(superclass, '<STR_LIT>') and superclass._meta.proxy:<EOL><INDENT>proxy_ancestor_classes.add(superclass)<EOL><DEDENT>proxy_ancestor_classes.update(<EOL>get_proxy_ancestor_classes(superclass))<EOL><DEDENT>return proxy_ancestor_cl...
Return a set containing all the proxy model classes that are ancestors of the given class. NOTE: This implementation is for Django 1.7, it might need to work differently for other versions especially 1.8+.
f4395:m5
@staticmethod<EOL><INDENT>def is_draft_request(request):<DEDENT>
return '<STR_LIT>' in request.GETor '<STR_LIT>' in request.GET<EOL>
Is this request explicly flagged as for draft content?
f4396:c0:m5
@staticmethod<EOL><INDENT>def is_draft(request):<DEDENT>
<EOL>if PublishingMiddleware.is_admin_request(request):<EOL><INDENT>return True<EOL><DEDENT>if PublishingMiddleware.is_api_request(request):<EOL><INDENT>return True<EOL><DEDENT>if PublishingMiddleware.is_draft_only_view(request):<EOL><INDENT>return True<EOL><DEDENT>if PublishingMiddleware.is_content_reviewer_user(reque...
A request is considered to be in draft mode if: - it is for *any* admin resource, since the admin site deals only with draft objects and hides the published version from admin users - it is for *any* view in *any* app that deals only with draft objects - user is a member of the "Content Reviewer" group, since content...
f4396:c0:m6
@staticmethod<EOL><INDENT>def redirect_staff_to_draft_view_on_404(request, response):<DEDENT>
if (response.status_code == <NUM_LIT><EOL>and not PublishingMiddleware.is_draft_request(request)<EOL>and not PublishingMiddleware.is_admin_request(request)<EOL>and not PublishingMiddleware.is_api_request(request)<EOL>and PublishingMiddleware.is_staff_user(request)):<EOL><INDENT>return HttpResponseRedirect(get_draft_url...
When a request fails with a 404, redirect to a (potential) draft version of the resource if the user is a staff member permitted to view drafts.
f4396:c0:m12
def _exchange_for_published(qs):
<EOL>published_version_pks = []<EOL>draft_version_pks = []<EOL>is_exchange_required = False<EOL>from .models import PublishingModel<EOL>if issubclass(qs.model, PublishingModel):<EOL><INDENT>for pk, publishing_is_draft, publishing_linked_id in qs.values_list(<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>if pu...
Exchange the results in a queryset of publishable items for the corresponding published copies. This means the result QS has: - already published items in original QS - the published copies for drafts with published versions - unpublished draft items in the original QS are removed. Unfortunately we cannot ...
f4397:m0
def _order_by_pks(qs, pks):
pk_colname = '<STR_LIT>' % (<EOL>qs.model._meta.db_table, qs.model._meta.pk.column)<EOL>clauses = '<STR_LIT:U+0020>'.join(<EOL>['<STR_LIT>' % (pk_colname, pk, i)<EOL>for i, pk in enumerate(pks)]<EOL>)<EOL>ordering = '<STR_LIT>' % clauses<EOL>return qs.extra(<EOL>select={'<STR_LIT>': ordering}, order_by=('<STR_LIT>',))<...
Adjust the given queryset to order items according to the explicit ordering of PKs provided. This is a PostgreSQL-specific DB hack, based on: blog.mathieu-leplatre.info/django-create-a-queryset-from-a-list-preserving-order.html
f4397:m1
def _queryset_visible(qs):
if is_draft_request_context():<EOL><INDENT>return qs.draft()<EOL><DEDENT>else:<EOL><INDENT>return qs.published()<EOL><DEDENT>
Return the visible version of publishable items, which means: - for privileged users: all draft items, whether published or not - for everyone else: the published copy of items.
f4397:m2
def _queryset_iterator(qs):
<EOL>if issubclass(type(qs), UrlNodeQuerySet):<EOL><INDENT>super_without_boobytrap_iterator = super(UrlNodeQuerySet, qs)<EOL><DEDENT>else:<EOL><INDENT>super_without_boobytrap_iterator = super(PublishingQuerySet, qs)<EOL><DEDENT>if is_publishing_middleware_active()and not is_draft_request_context():<EOL><INDENT>for item...
Override default iterator to wrap returned items in a publishing sanity-checker "booby trap" to lazily raise an exception if DRAFT items are mistakenly returned and mis-used in a public context where only PUBLISHED items should be used. This booby trap is added when all of: - the publishing middleware is active, and ...
f4397:m3
def get_draft_payload(self):
return self._draft_payload<EOL>
Get the wrapped payload directly, but only do this if you are *sure* you know what you are doing and cannot bypass the publishing checks another way!
f4397:c0:m2
def draft(self):
queryset = self.all()<EOL>return queryset.filter(publishing_is_draft=True)<EOL>
Filter items to only those that are actually draft, though each draft item may or may not have an associated published version. In most cases this filter will do no real work, since we almost always deal with only draft versions when interacting with publishable items.
f4397:c1:m1
def published(self, for_user=UNSET, force_exchange=False):
<EOL>if for_user is not UNSET:<EOL><INDENT>return self.visible()<EOL><DEDENT>queryset = self.all()<EOL>if force_exchange or self.exchange_on_published:<EOL><INDENT>queryset = queryset.exclude(<EOL>publishing_is_draft=True, publishing_linked=None)<EOL>return queryset.exchange_for_published()<EOL><DEDENT>else:<EOL><INDEN...
Transform the queryset to include published equivalents of items in it. This is a combination of filtering items that are published or have published versions, and exchanging (effectively the latter) for their published versions. By default, this method will apply a filter to find published items where `publishing_...
f4397:c1:m2
def only(self, *args, **kwargs):
field_names = args<EOL>if '<STR_LIT>' not in field_names:<EOL><INDENT>field_names += ('<STR_LIT>',)<EOL><DEDENT>return super(PublishingQuerySet, self).only(*field_names, **kwargs)<EOL>
Override default implementation to ensure that we *always* include the `publishing_is_draft` field when `only` is invoked, to avoid eternal recursion errors if `only` is called then we check for this item attribute in our custom `iterator`. Discovered the need for this by tracking down an eternal recursion error in th...
f4397:c1:m5
def published(self, for_user=UNSET, force_exchange=False):
if for_user is not UNSET:<EOL><INDENT>return self.visible()<EOL><DEDENT>queryset = super(PublishingUrlNodeQuerySet, self).published(<EOL>for_user=for_user, force_exchange=force_exchange)<EOL>queryset = queryset.exclude(<EOL>Q(publishing_is_draft=True) & Q(<EOL>Q(publishing_linked__publication_date__gt=now())<EOL>| Q(pu...
Apply additional filtering of published items over that done in `PublishingQuerySet.published` to filter based on additional publising date fields used by Fluent.
f4397:c3:m0
def published(self, for_user=None, force_exchange=True):
qs = self._single_site()<EOL>if for_user and is_draft_request_context():<EOL><INDENT>return qs<EOL><DEDENT>if for_user is not None and for_user.is_staff:<EOL><INDENT>pass <EOL><DEDENT>else:<EOL><INDENT>qs = qs.filter(<EOL>Q(publication_date__isnull=True) |<EOL>Q(publication_date__lt=now())<EOL>).filter(<EOL>Q(publicat...
Customise `UrlNodeQuerySet.published()` to add filtering by publication date constraints and exchange of draft items for published ones.
f4397:c4:m0
def monkey_patch_override_method(klass):
def perform_override(override_fn):<EOL><INDENT>fn_name = override_fn.__name__<EOL>original_fn_name = '<STR_LIT>' + fn_name<EOL>if not hasattr(klass, original_fn_name):<EOL><INDENT>original_fn = getattr(klass, fn_name)<EOL>setattr(klass, original_fn_name, original_fn)<EOL>setattr(klass, fn_name, override_fn)<EOL><DEDENT...
Override a class method with a new version of the same name. The original method implementation is made available within the override method as `_original_<METHOD_NAME>`.
f4398:m0
def monkey_patch_override_instance_method(instance):
def perform_override(override_fn):<EOL><INDENT>fn_name = override_fn.__name__<EOL>original_fn_name = '<STR_LIT>' + fn_name<EOL>if not hasattr(instance, original_fn_name):<EOL><INDENT>original_fn = getattr(instance, fn_name)<EOL>setattr(instance, original_fn_name, original_fn)<EOL>bound_override_fn = override_fn.__get__...
Override an instance method with a new version of the same name. The original method implementation is made available within the override method as `_original_<METHOD_NAME>`.
f4398:m1
def refresh(self, obj, obj_pk=None):
if obj_pk is None:<EOL><INDENT>obj_pk = obj.pk<EOL><DEDENT>return obj.__class__.objects.get(pk=obj_pk)<EOL>
Return the same object reloaded from the database, or optinally load an arbitrary object by PK if this ID is provided.
f4399:c0:m0
def assertNoFormErrorsInResponse(self, response):
errorlist_messages = [<EOL>l.strip()<EOL>for l in response.text.split('<STR_LIT:\n>')<EOL>if '<STR_LIT>' in l<EOL>]<EOL>self.assertEqual([], errorlist_messages)<EOL>
Fail if response content has any lines containing the 'errorlist' keyword, which indicates the form submission failed with errors.
f4399:c0:m2
def get_draft_hmac(salt, url):
return salted_hmac(salt, url, get_draft_secret_key()).hexdigest()<EOL>
Return a draft mode HMAC for the given salt and URL.
f4400:m2
def get_draft_secret_key():
<EOL>draft_secret_key, created = Text.objects.get_or_create(<EOL>name='<STR_LIT>',<EOL>defaults=dict(<EOL>value=get_random_string(<NUM_LIT:50>),<EOL>))<EOL>return draft_secret_key.value<EOL>
Return the secret key used to generate draft mode HMACs. It will be randomly generated on first access. Existing draft URLs can be invalidated by deleting or updating the ``DRAFT_SECRET_KEY`` setting.
f4400:m3
def get_draft_url(url):
if verify_draft_url(url):<EOL><INDENT>return url<EOL><DEDENT>url = urlparse.urlparse(url)<EOL>salt = get_random_string(<NUM_LIT:5>)<EOL>query = QueryDict(force_bytes(url.query), mutable=True)<EOL>query['<STR_LIT>'] = '<STR_LIT>' % (salt, get_draft_hmac(salt, url.path))<EOL>parts = list(url)<EOL>parts[<NUM_LIT:4>] = que...
Return the given URL with a draft mode HMAC in its querystring.
f4400:m4
def verify_draft_url(url):
url = urlparse.urlparse(url)<EOL>query = QueryDict(force_bytes(url.query))<EOL>preview_hmac = query.get('<STR_LIT>') or query.get('<STR_LIT>')<EOL>if preview_hmac:<EOL><INDENT>salt, hmac = preview_hmac.split('<STR_LIT::>')<EOL>return hmac == get_draft_hmac(salt, url.path)<EOL><DEDENT>return False<EOL>
Return ``True`` if the given URL has a valid draft mode HMAC in its querystring.
f4400:m5
def get_visible_object_or_404(klass, *args, **kwargs):
qs = _get_queryset(klass)<EOL>try:<EOL><INDENT>qs = qs.visible()<EOL><DEDENT>except AttributeError:<EOL><INDENT>pass <EOL><DEDENT>return get_object_or_404(qs, *args, **kwargs)<EOL>
Convenience replacement for `get_object_or_404` that automatically finds and returns only the *visible* copy of publishable items, or raises `Http404` if a visible copy is not available even when a draft copy is available.
f4400:m6
@receiver(publishing_signals.publishing_publish_save_draft)<EOL>@receiver(publishing_signals.publishing_unpublish_save_draft)<EOL>def save_draft_on_publish_and_unpublish(sender, instance, **kwargs):
instance.save()<EOL>
Save draft instance to associate it with, or disassociate it from, its published copy. Disconnect these signal handlers and reconnect with custom versions if you need more control over object saving in downstream projects, such as for saving version information with 'reversion'.
f4401:m0
@receiver(models.signals.pre_save)<EOL>def publishing_set_update_time(sender, instance, **kwargs):
if hasattr(instance, '<STR_LIT>'):<EOL><INDENT>if getattr(instance, '<STR_LIT>', False):<EOL><INDENT>instance._skip_update_publishing_modified_at = False<EOL>return<EOL><DEDENT>instance.publishing_modified_at = timezone.now()<EOL><DEDENT>
Update the time modified before saving a publishable object.
f4401:m1
@receiver(models.signals.m2m_changed)<EOL>def handle_publishable_m2m_changed(<EOL>sender, instance, action, reverse, model, pk_set, **kwargs):
<EOL>if not issubclass(model, PublishingModel):<EOL><INDENT>return<EOL><DEDENT>if reverse:<EOL><INDENT>for rel_obj in instance._meta.get_all_related_many_to_many_objects():<EOL><INDENT>if rel_obj.field.rel.through == sender:<EOL><INDENT>m2m = getattr(instance, rel_obj.get_accessor_name())<EOL>break<EOL><DEDENT><DEDENT>...
Cache related published objects in `pre_clear` so they can be restored in `post_clear`.
f4401:m2
@receiver(publishing_signals.publishing_post_publish)<EOL>def update_fluent_cached_urls_post_publish(sender, instance, **kwargs):
update_fluent_cached_urls(instance.publishing_linked)<EOL>
Update Fluent cached URLs for the published copy and its descendents
f4401:m3
@receiver(models.signals.post_save)<EOL>def sync_mptt_tree_fields_from_draft_to_published_post_save(<EOL>sender, instance, **kwargs):
mptt_opts = getattr(instance, '<STR_LIT>', None)<EOL>published_copy = getattr(instance, '<STR_LIT>', None)<EOL>if mptt_opts and published_copy:<EOL><INDENT>sync_mptt_tree_fields_from_draft_to_published(instance)<EOL><DEDENT>
Post save trigger to immediately sync MPTT tree structure field changes made to draft copies to their corresponding published copy.
f4401:m4
def sync_mptt_tree_fields_from_draft_to_published(<EOL>draft_copy, dry_run=False, force_update_cached_urls=False):
mptt_opts = getattr(draft_copy, '<STR_LIT>', None)<EOL>published_copy = getattr(draft_copy, '<STR_LIT>', None)<EOL>if not mptt_opts or not published_copy:<EOL><INDENT>return {}<EOL><DEDENT>parent_changed = draft_copy.parent != published_copy.parent<EOL>update_kwargs = {<EOL>mptt_opts.parent_attr: draft_copy._mpttfield(...
Sync tree structure changes from a draft publishable object to its published copy, and updates the published copy's Fluent cached URLs when necessary. Or simulates doing this if ``dry_run`` is ``True``. Syncs both actual structural changes (i.e. different parent) and MPTT's fields which are a cached representation (an...
f4401:m5
def update_fluent_cached_urls(item, dry_run=False):
change_report = []<EOL>if hasattr(item, '<STR_LIT>'):<EOL><INDENT>for translation in item.translations.all():<EOL><INDENT>old_url = translation._cached_url<EOL>item._update_cached_url(translation)<EOL>change_report.append(<EOL>(translation, '<STR_LIT>', old_url, translation._cached_url))<EOL>if not dry_run:<EOL><INDENT...
Regenerate the cached URLs for an item's translations. This is a fiddly business: we use "hidden" methods instead of the public ones to avoid unnecessary and unwanted slug changes to ensure uniqueness, the logic for which doesn't work with our publishing.
f4401:m6
@receiver(models.signals.post_migrate)<EOL>def create_can_publish_and_can_republish_permissions(sender, **kwargs):
for model in sender.get_models():<EOL><INDENT>if not issubclass(model, PublishingModel):<EOL><INDENT>continue<EOL><DEDENT>content_type = ContentType.objects.get_for_model(model)<EOL>permission, created = Permission.objects.get_or_create(<EOL>content_type=content_type, codename='<STR_LIT>',<EOL>defaults=dict(name='<STR_...
Add `can_publish` and `ca_nrepublish` permissions for each publishable model in the system.
f4401:m8
@receiver(publishing_signals.publishing_post_save_related)<EOL>def maybe_automatically_publish_drafts_on_save(sender, instance, **kwargs):
<EOL>if not is_automatic_publishing_enabled(sender):<EOL><INDENT>return<EOL><DEDENT>if not instance or not hasattr(instance, '<STR_LIT>'):<EOL><INDENT>return<EOL><DEDENT>if instance.is_published:<EOL><INDENT>return<EOL><DEDENT>if not instance.is_dirty:<EOL><INDENT>return<EOL><DEDENT>instance.publish()<EOL>
If automatic publishing is enabled, immediately publish a draft copy after it has been saved.
f4401:m9
@property<EOL><INDENT>def is_visible(self):<DEDENT>
if not is_draft_request_context():<EOL><INDENT>return self.is_published<EOL><DEDENT>else:<EOL><INDENT>return self.is_draft<EOL><DEDENT>
Return True if the item is the visible according to the request context: - for privileged users: is a draft item - for everyone else: is a published item
f4401:c0:m3
def is_within_publication_dates(obj, timestamp=None):
if timestamp is None:<EOL><INDENT>timestamp = timezone.now()<EOL><DEDENT>start_date_ok = not obj.publication_dateor obj.publication_date <= timestamp<EOL>end_date_ok = not obj.publication_end_dateor obj.publication_end_date > timestamp<EOL>return start_date_ok and end_date_ok<EOL>
Return True if the given timestamp (or ``now()`` by default) is witin any publication start/end date constraints.
f4401:c0:m4
@property<EOL><INDENT>def has_been_published(self):<DEDENT>
if self.is_published:<EOL><INDENT>return True<EOL><DEDENT>elif self.is_draft:<EOL><INDENT>return self.publishing_linked_id is not None<EOL><DEDENT>raise ValueError( <EOL>"<STR_LIT>" % self)<EOL>
Return True if the item is either published itself, or has an associated published copy. This is in contrast to ``is_published`` which only returns True if the specific object is a published copy, and will return False for a draft object that has an associated published copy.
f4401:c0:m5
def get_draft(self):
if self.is_draft:<EOL><INDENT>return self<EOL><DEDENT>elif self.is_published:<EOL><INDENT>draft = self.publishing_draft<EOL>if hasattr(draft, '<STR_LIT>'):<EOL><INDENT>draft = draft.get_draft_payload()<EOL><DEDENT>return draft<EOL><DEDENT>raise ValueError( <EOL>"<STR_LIT>" % self)<EOL>
Return self if this object is a draft, otherwise return the draft copy of a published item.
f4401:c0:m6
def get_published(self):
if self.is_published:<EOL><INDENT>return self<EOL><DEDENT>elif self.is_draft:<EOL><INDENT>return self.publishing_linked<EOL><DEDENT>raise ValueError( <EOL>"<STR_LIT>" % self)<EOL>
Return self is this object is published, otherwise return the published copy of a draft item. If this object is a draft with no published copy it will return ``None``.
f4401:c0:m7
def get_visible(self):
if is_draft_request_context():<EOL><INDENT>return self.get_draft()<EOL><DEDENT>else:<EOL><INDENT>return self.get_published()<EOL><DEDENT>
Return the visible version of publishable items, which means: - for privileged users: a draft items, whether published or not - for everyone else: the published copy of items.
f4401:c0:m8
def get_published_or_draft(self):
if self.is_published:<EOL><INDENT>return self<EOL><DEDENT>elif self.publishing_linked_id:<EOL><INDENT>return self.publishing_linked<EOL><DEDENT>if is_draft_request_context():<EOL><INDENT>return self.get_draft()<EOL><DEDENT>return None<EOL>
Return the published item, if it exists, otherwise, for privileged users, return the draft version.
f4401:c0:m9
@assert_draft<EOL><INDENT>def publish(self):<DEDENT>
if self.is_draft:<EOL><INDENT>if self.publishing_linked:<EOL><INDENT>self.patch_placeholders()<EOL>type(self.publishing_linked).objects.filter(pk=self.publishing_linked.pk).delete() <EOL><DEDENT>else:<EOL><INDENT>self.publishing_published_at = timezone.now()<EOL><DEDENT>publish_obj = deepcopy(self)<EOL>for fld in self...
Publishes the object. The decorator `assert_draft` makes sure that you cannot publish a published object. :param self: The object to tbe published. :return: The published object.
f4401:c0:m14
@assert_draft<EOL><INDENT>def unpublish(self):<DEDENT>
if self.is_draft and self.publishing_linked:<EOL><INDENT>publishing_signals.publishing_pre_unpublish.send(<EOL>sender=type(self), instance=self)<EOL>type(self.publishing_linked).objects.filter(pk=self.publishing_linked.pk).delete() <EOL>self.publishing_linked = None<EOL>self.publishing_published_at = None<EOL>publishi...
Un-publish the current object.
f4401:c0:m15
@assert_draft<EOL><INDENT>def revert_to_public(self):<DEDENT>
raise Exception(<EOL>"<STR_LIT>")<EOL>
Revert draft instance to the last published instance.
f4401:c0:m16
def publishing_prepare_published_copy(self, draft_obj):
<EOL>mysuper = super(PublishingModel, self)<EOL>if hasattr(mysuper, '<STR_LIT>'):<EOL><INDENT>mysuper.publishing_prepare_published_copy(draft_obj)<EOL><DEDENT>
Prepare published copy of draft prior to saving it
f4401:c0:m17
def publishing_clone_relations(self, src_obj):
def clone_through_model_relationship(<EOL>manager, through_entry, dst_obj, rel_obj<EOL>):<EOL><INDENT>dst_obj_filter = build_filter_for_through_field(<EOL>manager, manager.source_field_name, dst_obj)<EOL>rel_obj_filter = build_filter_for_through_field(<EOL>manager, manager.target_field_name, rel_obj)<EOL>if manager.thr...
Clone forward and reverse M2Ms. This code is difficult to follow because the logic it applies is confusing, but here is a summary that might help: - when a draft object is published, the "current" and definitive relationships are cloned to the published copy. The definitive relationships are the draft...
f4401:c0:m18
def clone_parler_translations(self, dst_obj):
<EOL>translation_attrs = []<EOL>if hasattr(self, '<STR_LIT>'):<EOL><INDENT>for parler_meta in self._parler_meta:<EOL><INDENT>translation_attrs.append(parler_meta.rel_name)<EOL><DEDENT><DEDENT>for translation_attr in translation_attrs:<EOL><INDENT>setattr(dst_obj, translation_attr, [])<EOL>for translation in getattr(sel...
Clone each of the translations from an object and relate them to another. :param self: The object to get the translations from. :param dst_obj: The object to relate the new translations to. :return: None
f4401:c0:m21
def clone_fluent_placeholders_and_content_items(self, dst_obj):
if not self.has_placeholder_relationships():<EOL><INDENT>return<EOL><DEDENT>for src_placeholder in Placeholder.objects.parent(self):<EOL><INDENT>dst_placeholder = Placeholder.objects.create_for_object(<EOL>dst_obj,<EOL>slot=src_placeholder.slot,<EOL>role=src_placeholder.role,<EOL>title=src_placeholder.title<EOL>)<EOL>s...
Clone each `Placeholder` and its `ContentItem`s. :param self: The object for which the placeholders are to be cloned from. :param dst_obj: The object which the cloned placeholders are to be related. :return: None
f4401:c0:m22
def clone_fluent_contentitems_m2m_relationships(self, dst_obj):
if not hasattr(self, '<STR_LIT>'):<EOL><INDENT>return<EOL><DEDENT>reliable_ordering = [<EOL>'<STR_LIT>',<EOL>'<STR_LIT>'<EOL>]<EOL>for src_ci, dst_ci in zip(<EOL>self.contentitem_set.order_by(*reliable_ordering),<EOL>dst_obj.contentitem_set.order_by(*reliable_ordering)<EOL>):<EOL><INDENT>for field, __ in src_ci._meta.g...
Find all MTM relationships on related ContentItem's and ensure the published M2M relationships directed back to the draft (src) content items are maintained for the published (dst) page's content items.
f4401:c0:m23
def suppressed_message(self):
return None<EOL>
Occasionally items may not be visible to the public even if they have been published and can be previewed. For example, if they belong to a parent who is not published. In that case, returning a string here will result in a red `published` indicator in admin, and the string will be shown in the hyperlink title. :retu...
f4401:c0:m24
@register.tag<EOL>def fake_request(parser, token):
return FakeRequestNode()<EOL>
Create a fake request object in the context
f4416:m0
@register.filter<EOL>def unescape(text):
def fixup(m):<EOL><INDENT>text = m.group(<NUM_LIT:0>)<EOL>if text[:<NUM_LIT:2>] == "<STR_LIT>":<EOL><INDENT>try:<EOL><INDENT>if text[:<NUM_LIT:3>] == "<STR_LIT>":<EOL><INDENT>return unichr(int(text[<NUM_LIT:3>:-<NUM_LIT:1>], <NUM_LIT:16>))<EOL><DEDENT>else:<EOL><INDENT>return unichr(int(text[<NUM_LIT:2>:-<NUM_LIT:1>]))...
Removes HTML or XML character references and entities from a text string. :param text: The HTML (or XML) source text. :return: The plain text, as a Unicode string, if necessary.
f4416:m1
def get_item(obj, key):
try:<EOL><INDENT>return obj[key]<EOL><DEDENT>except KeyError:<EOL><INDENT>return None<EOL><DEDENT>
Obtain an item in a dictionary style object. :param obj: The object to look up the key on. :param key: The key to lookup. :return: The contents of the the dictionary lookup.
f4417:m0
@register.assignment_tag(name='<STR_LIT>')<EOL>def get_slot_contents_tag(descriptor, slot_name):
return get_item(descriptor, slot_name)<EOL>
`get_slot_contents` accepts arguments in the format: `{% get_slot_contents <slot descriptor> <slot name> as <variable_name> %}`
f4417:m1
def grammatical_join(l, initial_joins="<STR_LIT:U+002CU+0020>", final_join="<STR_LIT>"):
<EOL>return initial_joins.join(l[:-<NUM_LIT:2>] + [final_join.join(l[-<NUM_LIT:2>:])])<EOL>
Display a list of items nicely, with a different string before the final item. Useful for using lists in sentences. >>> grammatical_join(['apples', 'pears', 'bananas']) 'apples, pears and bananas' >>> grammatical_join(['apples', 'pears', 'bananas'], initial_joins=";", final_join="; or ") 'apples; pears; or bananas' ...
f4417:m3
def _grammatical_join_filter(l, arg=None):
if not arg:<EOL><INDENT>arg = "<STR_LIT>"<EOL><DEDENT>try:<EOL><INDENT>final_join, initial_joins = arg.split("<STR_LIT:|>")<EOL><DEDENT>except ValueError:<EOL><INDENT>final_join = arg<EOL>initial_joins = "<STR_LIT:U+002CU+0020>"<EOL><DEDENT>return grammatical_join(l, initial_joins, final_join)<EOL>
:param l: List of strings to join :param arg: A pipe-separated list of final_join (" and ") and initial_join (", ") strings. For example :return: A string that grammatically concatenates the items in the list.
f4417:m4
@register.tag(name='<STR_LIT>')<EOL>def update_GET(parser, token):
try:<EOL><INDENT>args = token.split_contents()[<NUM_LIT:1>:]<EOL>triples = list(_chunks(args, <NUM_LIT:3>))<EOL>if triples and len(triples[-<NUM_LIT:1>]) != <NUM_LIT:3>:<EOL><INDENT>raise template.TemplateSyntaxError("<STR_LIT>" % token.contents.split()[<NUM_LIT:0>])<EOL><DEDENT>ops = set([t[<NUM_LIT:1>] for t in tripl...
``update_GET`` allows you to substitute parameters into the current request's GET parameters. This is useful for updating search filters, page numbers, without losing the current set. For example, the template fragment:: <a href="?{% update_GET 'attr1' += value1 'attr2' -= value2 'attr3' = value3 %}">foo</a> ...
f4417:m5
def _chunks(l, n):
for i in range(<NUM_LIT:0>, len(l), n):<EOL><INDENT>yield l[i:i+n]<EOL><DEDENT>
Yield successive n-sized chunks from l.
f4417:m6
def fix_ampersands(value):
return unencoded_ampersands_re.sub('<STR_LIT>', force_text(value))<EOL>
Returns given HTML with all unencoded ampersands encoded correctly.
f4417:m7
@register.filter<EOL>def oembed(url, params="<STR_LIT>"):
<EOL>kwargs = dict(urllib.parse.parse_qsl(params))<EOL>try:<EOL><INDENT>return mark_safe(get_oembed_data(<EOL>url,<EOL>**kwargs<EOL>)['<STR_LIT:html>'])<EOL><DEDENT>except (KeyError, ProviderException):<EOL><INDENT>if settings.DEBUG:<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>return "<STR_LIT>"<EOL><DEDENT>
Render an OEmbed-compatible link as an embedded item. :param url: A URL of an OEmbed provider. :return: The OEMbed ``<embed>`` code.
f4417:m8
@register.filter<EOL>def admin_link(obj):
if hasattr(obj, '<STR_LIT>'):<EOL><INDENT>return mark_safe(obj.get_admin_link())<EOL><DEDENT>return mark_safe(admin_link_fn(obj))<EOL>
Returns a link to the admin URL of an object. No permissions checking is involved, so use with caution to avoid exposing the link to unauthorised users. Example:: {{ foo_obj|admin_link }} renders as:: <a href='/admin/foo/123'>Foo</a> :param obj: A Django model instance. :return: A safe string expressing a...
f4417:m9
@register.filter<EOL>def admin_url(obj):
if hasattr(obj, '<STR_LIT>'):<EOL><INDENT>return mark_safe(obj.get_admin_url())<EOL><DEDENT>return mark_safe(admin_url_fn(obj))<EOL>
Returns the admin URL of the object. No permissions checking is involved, so use with caution to avoid exposing the link to unauthorised users. Example:: {{ foo_obj|admin_url }} renders as:: /admin/foo/123 :param obj: A Django model instance. :return: the admin URL of the object
f4417:m10
@register.filter<EOL>def link(obj):
return mark_safe("<STR_LIT>".format(obj.get_absolute_url(), str(obj)))<EOL>
Returns a link to the object. The URL of the link is ``obj.get_absolute_url()``, and the text of the link is ``unicode(obj)``. Example:: {{ foo_obj|link }} renders as:: <a href='/foo/'>Foo</a> :param obj: A Django model instance. :return: A safe string expressing an HTML link to the object.
f4417:m11
@register.tag<EOL>def deprecate_and_include(parser, token):
split_contents = token.split_contents()<EOL>current_template = split_contents[<NUM_LIT:1>]<EOL>new_template = split_contents[<NUM_LIT:2>]<EOL>if settings.DEBUG:<EOL><INDENT>warnings.simplefilter('<STR_LIT>', DeprecationWarning)<EOL><DEDENT>warnings.warn("<STR_LIT>" % (current_template, new_template), DeprecationWarning...
Raises a deprecation warning about using the first argument. The remaining arguments are passed to an ``{% include %}`` tag. Usage:: {% deprecate_and_include "old_template.html" "new_template.html" %} In order to avoid re-implementing {% include %} so as to resolve variables, this tag currently only works with li...
f4417:m12
@register.filter<EOL>def sharedcontent_exists(slug):
from django.contrib.sites.models import Site<EOL>from fluent_contents.plugins.sharedcontent.models import SharedContent<EOL>site = Site.objects.get_current()<EOL>return SharedContent.objects.parent_site(site).filter(slug=slug).exists()<EOL>
Return `True` if shared content with the given slug name exists. This filter makes it possible to conditionally include shared content with surrounding markup only when the shared content item actually exits, and avoid outputting the surrounding markup when it doesn't. Example usage: {% load icekit_tags sharedco...
f4417:m13
def template_name(value):
try:<EOL><INDENT>loader.get_template(value)<EOL><DEDENT>except TemplateDoesNotExist:<EOL><INDENT>raise ValidationError(<EOL>_('<STR_LIT>'), code='<STR_LIT>')<EOL><DEDENT>
Validate that a ``value`` is a valid template name.
f4426:m0
def get_users_for_assigned_to():
User = get_user_model()<EOL>return User.objects.filter(is_active=True, is_staff=True)<EOL>
Return a list of users who can be assigned to workflow states
f4431:m0
def _get_obj_ct(self, obj):
if not hasattr(obj, '<STR_LIT>'):<EOL><INDENT>if hasattr(obj, '<STR_LIT>'):<EOL><INDENT>obj._wfct = obj.polymorphic_ctype<EOL><DEDENT>else:<EOL><INDENT>obj._wfct = ContentType.objects.get_for_model(obj)<EOL><DEDENT><DEDENT>return obj._wfct<EOL>
Look up and return object's content type and cache for reuse
f4431:c4:m0