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_historical<EOL><DEDENT><DEDENT>return r<EOL>
: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(<EOL>role=data.role,<EOL>title=data.title,<EOL>))<EOL>result = result or created<EOL><DEDENT><DEDENT>return result<EOL>
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_plural)<EOL>
: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_LIT>'),<EOL>'<STR_LIT:description>': [<EOL>line for line in self.map_description.splitlines() if line<EOL>],<EOL>}<EOL>
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>ctypes.append(ContentType.objects.get_for_model(child).pk)<EOL><DEDENT><DEDENT><DEDENT>return ctypes<EOL>
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>placeholders = [p.as_dict() for p in placeholders]<EOL>for p in placeholders:<EOL><INDENT>try:<EOL><INDENT>p['<STR_LIT>'] = settings.FLUENT_CONTENTS_PLACEHOLDER_CONFIG.get(p['<STR_LIT>']).get('<STR_LIT>')<EOL><DEDENT>except AttributeError:<EOL><INDENT>p['<STR_LIT>'] = None<EOL><DEDENT><DEDENT>json = {<EOL>'<STR_LIT:id>': layout.id,<EOL>'<STR_LIT:title>': layout.title,<EOL>'<STR_LIT>': placeholders,<EOL>}<EOL><DEDENT>return JsonResponse(json, status=status)<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_field in unique_fields:<EOL><INDENT>field = instance.get_field(unique_field)<EOL>if field.editable and unique_field in cleaned_data:<EOL><INDENT>unique_filter[unique_field] = cleaned_data[unique_field]<EOL><DEDENT>else:<EOL><INDENT>unique_filter[unique_field] =getattr(instance, unique_field)<EOL><DEDENT><DEDENT>existing_instances = type(instance).objects.filter(**unique_filter).exclude(pk=instance.pk)<EOL>if instance.publishing_linked:<EOL><INDENT>existing_instances = existing_instances.exclude(<EOL>pk=instance.publishing_linked.pk)<EOL><DEDENT>if existing_instances:<EOL><INDENT>for unique_field in unique_fields:<EOL><INDENT>self._errors[unique_field] = self.error_class(<EOL>[_('<STR_LIT>')])<EOL><DEDENT><DEDENT><DEDENT>return data<EOL>
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 True<EOL><DEDENT>if user_obj.has_perm('<STR_LIT>' % self.opts.app_label) andobj and getattr(obj, '<STR_LIT>', False):<EOL><INDENT>return True<EOL><DEDENT>return False<EOL>
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 - the view code for a particular item, which may or may not render draft content for a specific user. :param request: Django request object. :param obj: The object the user would preview, if permitted. :return: Boolean.
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 = Context({<EOL>'<STR_LIT:object>': obj,<EOL>'<STR_LIT>': object_url,<EOL>'<STR_LIT>':<EOL>self.has_publish_permission(self.request, obj),<EOL>'<STR_LIT>':<EOL>self.has_preview_permission(self.request, obj),<EOL>})<EOL>try:<EOL><INDENT>if isinstance(obj, PublishingModel):<EOL><INDENT>c['<STR_LIT>'] = reverse(<EOL>self.publish_reverse(type(obj)), args=(obj.pk, ))<EOL>c['<STR_LIT>'] = reverse(<EOL>self.unpublish_reverse(type(obj)), args=(obj.pk, ))<EOL><DEDENT><DEDENT>except NoReverseMatch:<EOL><INDENT>pass<EOL><DEDENT>return t.render(c)<EOL>
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>ordering = getattr(self, '<STR_LIT>', None) or ()<EOL>if ordering:<EOL><INDENT>qs = qs.order_by(*ordering)<EOL><DEDENT>return qs<EOL>
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>context['<STR_LIT>'] = False<EOL><DEDENT>else:<EOL><INDENT>context['<STR_LIT>'] = True<EOL>try:<EOL><INDENT>object_url = obj.get_absolute_url()<EOL><DEDENT>except (NoReverseMatch, AttributeError):<EOL><INDENT>object_url = '<STR_LIT>'<EOL><DEDENT>publish_btn = None<EOL>if obj.is_dirty:<EOL><INDENT>publish_btn = reverse(<EOL>self.publish_reverse(type(obj)), args=(obj.pk, ))<EOL><DEDENT>unpublish_btn = None<EOL>if obj.is_draft and obj.publishing_linked:<EOL><INDENT>unpublish_btn = reverse(<EOL>self.unpublish_reverse(type(obj)), args=(obj.pk, ))<EOL><DEDENT>revert_btn = None<EOL>if obj.is_dirty and obj.publishing_linked:<EOL><INDENT>revert_btn = reverse(self.revert_reverse, args=(obj.pk, ))<EOL><DEDENT>context.update({<EOL>'<STR_LIT>': object_url,<EOL>'<STR_LIT>': publish_btn,<EOL>'<STR_LIT>': unpublish_btn,<EOL>'<STR_LIT>': revert_btn,<EOL>})<EOL><DEDENT><DEDENT>context.update({<EOL>'<STR_LIT>':<EOL>self.non_publishing_change_form_template,<EOL>'<STR_LIT>':<EOL>self.non_publishing_change_form_template,<EOL>})<EOL>try:<EOL><INDENT>self.update_context_for_render_change_form(context, obj)<EOL><DEDENT>except AttributeError:<EOL><INDENT>pass<EOL><DEDENT>if hasattr(type(self).change_form_template, '<STR_LIT>')and isinstance(self.change_form_template, (list, tuple)):<EOL><INDENT>opts = self.model._meta<EOL>app_label = opts.app_label<EOL>extra_change_form_templates = [<EOL>"<STR_LIT>" % (<EOL>app_label, opts.model_name),<EOL>"<STR_LIT>" % app_label,<EOL>"<STR_LIT>"<EOL>]<EOL>context['<STR_LIT>'] =self.find_first_available_template(<EOL>extra_change_form_templates + self.change_form_template)<EOL>try:<EOL><INDENT>self._change_form_template_getter =type(self).change_form_template.__get__<EOL>type(self).change_form_template =context['<STR_LIT>']<EOL>has_change_form_attr_getter = True<EOL><DEDENT>except AttributeError:<EOL><INDENT>self.change_form_template =context['<STR_LIT>']<EOL>has_change_form_attr_getter = False<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self.change_form_template ="<STR_LIT>"<EOL>has_change_form_attr_getter = False<EOL><DEDENT>response = super(PublishingAdmin, self).render_change_form(<EOL>request, context,<EOL>add=add, change=change, form_url=form_url, obj=obj)<EOL>if has_change_form_attr_getter:<EOL><INDENT>type(self).change_form_template =self._change_form_template_getter<EOL><DEDENT>else:<EOL><INDENT>self.change_form_template =self.non_publishing_change_form_template<EOL><DEDENT>return response<EOL>
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 to use for the form submit action. :param obj: An object the render change form is for.
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_classes<EOL>
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(request):<EOL><INDENT>return True<EOL><DEDENT>if PublishingMiddleware.is_draft_request(request):<EOL><INDENT>if PublishingMiddleware.is_staff_user(request):<EOL><INDENT>return True<EOL><DEDENT>if verify_draft_url(request.get_full_path()):<EOL><INDENT>return True<EOL><DEDENT><DEDENT>return False<EOL>
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 reviewers' sole purpose is to review draft content and they need not see the published content - the user is a staff member and therefore can see draft versions of pages if they wish, and the 'preview' GET parameter flag is included to show the draft page is definitely wanted instead of a normal published page. - the 'preview' GET parameter flag is included with a valid HMAC for the requested URL, regardless of authenticated permissions.
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(request.get_full_path()))<EOL><DEDENT>return response<EOL>
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 publishing_is_draft:<EOL><INDENT>draft_version_pks.append(pk)<EOL>if publishing_linked_id:<EOL><INDENT>published_version_pks.append(publishing_linked_id)<EOL>is_exchange_required = True<EOL><DEDENT><DEDENT>elif not publishing_is_draft:<EOL><INDENT>published_version_pks.append(pk)<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>for item in qs:<EOL><INDENT>if getattr(item, '<STR_LIT>', None):<EOL><INDENT>draft_version_pks.append(item.pk)<EOL>if getattr(item, '<STR_LIT>', None):<EOL><INDENT>published_version_pks.append(item.publishing_linked_id)<EOL>is_exchange_required = True<EOL><DEDENT><DEDENT>elif getattr(item, '<STR_LIT>', None):<EOL><INDENT>published_version_pks.append(item.pk)<EOL><DEDENT><DEDENT><DEDENT>if not is_exchange_required:<EOL><INDENT>return qs.exclude(pk__in=draft_version_pks)<EOL><DEDENT>else:<EOL><INDENT>qs = qs.model.objects.filter(pk__in=published_version_pks)<EOL>qs = _order_by_pks(qs, published_version_pks)<EOL>return qs<EOL><DEDENT>
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 just perform a normal queryset filter operation in the DB because FK/M2M relationships assigned in the site admin are *always* to draft objects. Instead we exchange draft items for published copies.
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>',))<EOL>
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 in super_without_boobytrap_iterator.iterator():<EOL><INDENT>if getattr(item, '<STR_LIT>', False):<EOL><INDENT>yield DraftItemBoobyTrap(item)<EOL><DEDENT>else:<EOL><INDENT>yield item<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>for item in super_without_boobytrap_iterator.iterator():<EOL><INDENT>yield item<EOL><DEDENT><DEDENT>
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 therefore able to report accurately whether the request is in a drafts-permitted context - the publishing middleware tells us we are not in a drafts-permitted context, which means only published items should be used.
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><INDENT>return queryset.filter(publishing_is_draft=False)<EOL><DEDENT>
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_is_draft==False`. If it is necessary to exchange draft items for published copies, such as for relationships defined in the admin that only capture draft targets, the exchange mechanism is triggered either by forcing it with `force_exchange==True` or by enabling exchange by default at the class level with `exchange_on_published==True`. In either case, this method will return only the published object copies of published items. It should be noted that Fluent's notion of "published" items is different from ours and is user-sensitive such that privileged users actually see draft items as published. To make Fluent's notion of published items align with ours this method also acts as a shim for our ``visible`` filter and will return visible items when invoked by Fluent's view resolution process that provides the ``for_user`` kwarg.
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 the `only` query performed in fluent_pages.urlresolvers._get_pages_of_type
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(publishing_linked__publication_end_date__lte=now())))<EOL>queryset = queryset.exclude(<EOL>Q(publishing_is_draft=False) & Q(<EOL>Q(publication_date__gt=now())<EOL>| Q(publication_end_date__lte=now())))<EOL>return queryset<EOL>
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(publication_end_date__isnull=True) |<EOL>Q(publication_end_date__gte=now())<EOL>)<EOL><DEDENT>if force_exchange:<EOL><INDENT>return _exchange_for_published(qs)<EOL><DEDENT>else:<EOL><INDENT>return qs.filter(status=UrlNode.PUBLISHED)<EOL><DEDENT>
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><DEDENT>return perform_override<EOL>
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__(instance)<EOL>setattr(instance, fn_name, bound_override_fn)<EOL><DEDENT><DEDENT>return perform_override<EOL>
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>] = query.urlencode(safe='<STR_LIT::>')<EOL>return urlparse.urlunparse(parts)<EOL>
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><DEDENT>else:<EOL><INDENT>for field in instance._meta.many_to_many:<EOL><INDENT>if field.rel.through == sender:<EOL><INDENT>m2m = getattr(instance, field.attname)<EOL>break<EOL><DEDENT><DEDENT><DEDENT>if action == '<STR_LIT>':<EOL><INDENT>instance._published_m2m_cache = set(<EOL>m2m.filter(publishing_is_draft=False).values_list('<STR_LIT>', flat=True))<EOL><DEDENT>if action == '<STR_LIT>':<EOL><INDENT>m2m.add(*instance._published_m2m_cache)<EOL>del instance._published_m2m_cache<EOL><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('<STR_LIT>'),<EOL>mptt_opts.tree_id_attr: draft_copy._mpttfield('<STR_LIT>'),<EOL>mptt_opts.left_attr: draft_copy._mpttfield('<STR_LIT:left>'),<EOL>mptt_opts.right_attr: draft_copy._mpttfield('<STR_LIT:right>'),<EOL>mptt_opts.level_attr: draft_copy._mpttfield('<STR_LIT>'),<EOL>}<EOL>update_kwargs = dict(<EOL>(field, value) for field, value in update_kwargs.items()<EOL>if getattr(draft_copy, field) != getattr(published_copy, field)<EOL>and not (field != '<STR_LIT>' and value is None)<EOL>)<EOL>change_report = []<EOL>for field, new_value in update_kwargs.items():<EOL><INDENT>old_value = getattr(published_copy, field)<EOL>change_report.append((draft_copy, field, old_value, new_value))<EOL><DEDENT>if update_kwargs and not dry_run:<EOL><INDENT>type(published_copy).objects.filter(pk=published_copy.pk).update(<EOL>**update_kwargs)<EOL><DEDENT>if parent_changed or force_update_cached_urls:<EOL><INDENT>published_copy.parent = draft_copy.parent<EOL>change_report +=update_fluent_cached_urls(published_copy, dry_run=dry_run)<EOL><DEDENT>return change_report<EOL>
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 (and may or may not be correct).
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>translation.save()<EOL><DEDENT><DEDENT>if not dry_run:<EOL><INDENT>item._expire_url_caches()<EOL><DEDENT>if item.is_draft:<EOL><INDENT>children = [child for child in item.children.all()<EOL>if child.is_draft]<EOL><DEDENT>else:<EOL><INDENT>children = [child for child in item.get_draft().children.all()<EOL>if child.is_published]<EOL><DEDENT>for child in children:<EOL><INDENT>update_fluent_cached_urls(child, dry_run=dry_run)<EOL><DEDENT><DEDENT>return change_report<EOL>
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_LIT>' % model.__name__))<EOL>permission, created = Permission.objects.get_or_create(<EOL>content_type=content_type, codename='<STR_LIT>',<EOL>defaults=dict(name='<STR_LIT>' % model.__name__))<EOL><DEDENT>
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.publishing_publish_empty_fields + (<EOL>'<STR_LIT>', '<STR_LIT>'<EOL>):<EOL><INDENT>setattr(publish_obj, fld, None)<EOL><DEDENT>publish_obj.publishing_is_draft = False<EOL>if isinstance(self, UrlNode):<EOL><INDENT>self.status = UrlNode.DRAFT<EOL>publish_obj.status = UrlNode.PUBLISHED<EOL><DEDENT>publish_obj.publishing_published_at = self.publishing_published_at<EOL>publish_obj.publishing_prepare_published_copy(self)<EOL>publish_obj.save()<EOL>if not publish_obj.pk: <EOL><INDENT>raise PublishingException("<STR_LIT>")<EOL><DEDENT>self.clone_parler_translations(publish_obj)<EOL>self.clone_fluent_placeholders_and_content_items(publish_obj)<EOL>self.clone_fluent_contentitems_m2m_relationships(publish_obj)<EOL>publish_obj.publishing_clone_relations(self)<EOL>self.publishing_linked = publish_obj<EOL>self._skip_update_publishing_modified_at = True<EOL>publishing_signals.publishing_publish_pre_save_draft.send(<EOL>sender=type(self), instance=self)<EOL>publishing_signals.publishing_publish_save_draft.send(<EOL>sender=type(self), instance=self)<EOL>publishing_signals.publishing_post_publish.send(<EOL>sender=type(self), instance=self)<EOL>return publish_obj<EOL><DEDENT>
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>publishing_signals.publishing_unpublish_save_draft.send(<EOL>sender=type(self), instance=self)<EOL>publishing_signals.publishing_post_unpublish.send(<EOL>sender=type(self), instance=self)<EOL><DEDENT>
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.through.objects.filter(**dst_obj_filter).filter(**rel_obj_filter).exists():<EOL><INDENT>return<EOL><DEDENT>through_entry.pk = None<EOL>setattr(through_entry, manager.source_field_name, dst_obj)<EOL>setattr(through_entry, manager.target_field_name, rel_obj)<EOL>through_entry.save()<EOL><DEDENT>def delete_through_model_relationship(manager, src_obj, dst_obj):<EOL><INDENT>src_obj_filter = build_filter_for_through_field(<EOL>manager, manager.source_field_name, src_obj)<EOL>dst_obj_filter = build_filter_for_through_field(<EOL>manager, manager.target_field_name, dst_obj)<EOL>manager.through.objects.filter(**src_obj_filter).filter(**dst_obj_filter).delete()<EOL><DEDENT>def build_filter_for_through_field(manager, field_name, obj):<EOL><INDENT>field = getattr(manager.through, field_name)<EOL>if isinstance(field, GenericForeignKey):<EOL><INDENT>field_filter = {<EOL>getattr(field, '<STR_LIT>'): obj.pk,<EOL>getattr(field, '<STR_LIT>'):<EOL>ContentType.objects.get_for_model(obj)<EOL>}<EOL><DEDENT>else:<EOL><INDENT>field_filter = {field_name: obj}<EOL><DEDENT>return field_filter<EOL><DEDENT>def clone(src_manager):<EOL><INDENT>if (<EOL>not hasattr(src_manager, '<STR_LIT>') or<EOL>not hasattr(src_manager, '<STR_LIT>')<EOL>):<EOL><INDENT>raise PublishingException(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>)<EOL><DEDENT>src_obj_source_field_filter = build_filter_for_through_field(<EOL>src_manager, src_manager.source_field_name, src_obj)<EOL>through_qs = src_manager.through.objects.filter(**src_obj_source_field_filter)<EOL>published_rel_objs_maybe_obsolete = []<EOL>current_draft_rel_pks = set()<EOL>for through_entry in through_qs:<EOL><INDENT>rel_obj = getattr(through_entry, src_manager.target_field_name)<EOL>if getattr(rel_obj, '<STR_LIT>', True):<EOL><INDENT>clone_through_model_relationship(<EOL>src_manager, through_entry, self, rel_obj)<EOL>try:<EOL><INDENT>rel_obj_published = rel_obj.publishing_linked<EOL><DEDENT>except AttributeError:<EOL><INDENT>pass <EOL><DEDENT>else:<EOL><INDENT>if rel_obj_published:<EOL><INDENT>clone_through_model_relationship(<EOL>src_manager, through_entry,<EOL>src_obj, rel_obj_published)<EOL><DEDENT><DEDENT>current_draft_rel_pks.add(rel_obj.pk)<EOL><DEDENT>else:<EOL><INDENT>published_rel_objs_maybe_obsolete.append(rel_obj)<EOL><DEDENT><DEDENT>for published_rel_obj in published_rel_objs_maybe_obsolete:<EOL><INDENT>draft = published_rel_obj.get_draft()<EOL>if not draft or draft.pk not in current_draft_rel_pks:<EOL><INDENT>delete_through_model_relationship(<EOL>src_manager, src_obj, published_rel_obj)<EOL><DEDENT><DEDENT><DEDENT>seen_rel_through_tables = set()<EOL>for field in src_obj._meta.many_to_many:<EOL><INDENT>src_manager = getattr(src_obj, field.name)<EOL>clone(src_manager)<EOL>seen_rel_through_tables.add(field.rel.through)<EOL><DEDENT>for field in src_obj._meta.get_all_related_many_to_many_objects():<EOL><INDENT>if field.field.rel.through in seen_rel_through_tables:<EOL><INDENT>continue<EOL><DEDENT>field_accessor_name = field.get_accessor_name()<EOL>if not field_accessor_name:<EOL><INDENT>continue<EOL><DEDENT>src_manager = getattr(src_obj, field_accessor_name)<EOL>clone(src_manager)<EOL><DEDENT>
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-to-draft ones, as set in the admin. - a "related draft" is the draft object at the other side of a draft-to-draft M2M relationship - if a related draft also has a published copy, a draft-to- published relationship is added to that published copy. This makes our newly-published item also "published" from the reverse direction - if our draft object has a related published copy without a correponding related draft -- that is, a draft-to-published relation without a definitive draft-to-draft relation -- then we remove that relation as it is no longer "current". This makes our newly-published item "unpublished" from the reverse direction when an admin removes the underlying relationship. An example case: - We have Event "E" (unpublished) and Program "P" (published) - We add an M2M relationship from E to P. Until the relationship change is published it only affects drafts. Relationships are: E draft <-> P draft - We publish E, applying the relationship to published copies on both sides: E draft <-> P draft E published <-> P draft P published <-> E draft - We remove the M2M relationship between E and P (We could do this from either side: remove E from P; or, remove P from E). The draft-to-draft relation is removed but published copy relationships are not affected: E published <-> P draft P published <-> E draft - We publish P (or E) to apply the relationshp removal to published copies on both sides. No relationships remain. To handle M2M relationships in general we iterate over entries in the through-table relationship table to clone these entries, or remove them, as appropriate. By processing the M2M relationships in this way we can handle both kinds of M2M relationship: - standard M2M relationships with no explicit through table defined (these get an auto-generated through table) which are easier to handle because we can add/remove items with the relationship's queryset directly - M2M relationships with an explicit through table defined, which are more difficult to handle because we must use the through model's manager to add/remove relationships. See unit tests in ``TestPublishingOfM2MRelationships``.
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(self, translation_attr).all():<EOL><INDENT>translation.pk = None<EOL>translation.master = dst_obj<EOL>translation.save()<EOL><DEDENT><DEDENT>
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>src_items = src_placeholder.get_content_items()<EOL>src_items.copy_to_placeholder(dst_placeholder)<EOL><DEDENT>
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.get_m2m_with_model():<EOL><INDENT>field_name = field.name<EOL>src_m2m = getattr(src_ci, field_name)<EOL>dst_m2m = getattr(dst_ci, field_name)<EOL>dst_m2m.add(*src_m2m.all())<EOL><DEDENT><DEDENT>
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. :return: A message to be shown to the user only if the content can be previewed but not published.
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>]))<EOL><DEDENT><DEDENT>except ValueError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>text = unichr(htmlentitydefs.name2codepoint[text[<NUM_LIT:1>:-<NUM_LIT:1>]])<EOL><DEDENT>except KeyError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>return text <EOL><DEDENT>return re.sub("<STR_LIT>", fixup, text)<EOL>
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' :param l: List of strings to join :param initial_joins: the string to join the non-ultimate items with :param final_join: the string to join the final item with :return: items joined with commas except " and " before the final one.
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 triples])<EOL>if not ops <= set(['<STR_LIT>', '<STR_LIT>', '<STR_LIT:=>']):<EOL><INDENT>raise template.TemplateSyntaxError("<STR_LIT>" % "<STR_LIT:U+002CU+0020>".join(ops))<EOL><DEDENT><DEDENT>except ValueError:<EOL><INDENT>return UpdateGetNode()<EOL><DEDENT>return UpdateGetNode(triples)<EOL>
``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> - adds ``value1`` to (the list of values in) ``'attr1'``, - removes ``value2`` from (the list of values in) ``'attr2'``, - sets ``attr3`` to ``value3``. and returns a urlencoded GET string. Allowed attributes are: - strings, in quotes - vars that resolve to strings Allowed values are: - strings, in quotes - vars that resolve to strings - lists of strings - None (without quotes) Note: - If a attribute is set to ``None`` or an empty list, the GET parameter is removed. - If an attribute's value is an empty string, or ``[""]`` or ``None``, the value remains, but has a ``""`` value. - If you try to ``=-`` a value from a list that doesn't contain that value, nothing happens. - If you try to ``=-`` a value from a list where the value appears more than once, only the first value is removed.
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 an HTML link to the admin page for an object.
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, stacklevel=<NUM_LIT:2>)<EOL>new_contents = [split_contents[<NUM_LIT:0>]] + split_contents[<NUM_LIT:2>:]<EOL>include_token = Token(token.token_type, "<STR_LIT:U+0020>".join(new_contents))<EOL>return do_include(parser, include_token)<EOL>
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 literal template path strings.
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 sharedcontent_tags %} {% if "shared-content-slug"|sharedcontent_exists %} <div class="surrounding-html"> {% sharedcontent "shared-content-slug" %} </div> {% endif %}
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