signature
stringlengths
8
3.44k
body
stringlengths
0
1.41M
docstring
stringlengths
1
122k
id
stringlengths
5
17
@register.filter<EOL>def filter_featured_apps(admin_apps, request):
featured_apps = []<EOL>for orig_app_spec in appsettings.DASHBOARD_FEATURED_APPS:<EOL><INDENT>app_spec = orig_app_spec.copy()<EOL>if "<STR_LIT>" in app_spec:<EOL><INDENT>warnings.warn(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>" % app_spec['<STR_LIT>'],<EOL>DeprecationWarning, stacklevel=<NUM_LIT:2><EOL>)<EOL>app_spec['<STR_LIT:name>'] = app_spec['<STR_LIT>']<EOL><DEDENT>if hasattr(app_spec['<STR_LIT>'], '<STR_LIT>'):<EOL><INDENT>warnings.warn(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>" % app_spec['<STR_LIT:name>'],<EOL>DeprecationWarning, stacklevel=<NUM_LIT:2><EOL>)<EOL>app_spec['<STR_LIT>'] = app_spec['<STR_LIT>'].items()<EOL><DEDENT>app_spec['<STR_LIT>'] = _build_app_models(<EOL>request, admin_apps, app_spec['<STR_LIT>']<EOL>)<EOL>if app_spec['<STR_LIT>']:<EOL><INDENT>featured_apps.append(app_spec)<EOL><DEDENT><DEDENT>return featured_apps<EOL>
Given a list of apps return a set of pseudo-apps considered featured. Apps are considered featured if the are defined in the settings property called `DASHBOARD_FEATURED_APPS` which contains a list of the apps that are considered to be featured. :param admin_apps: A list of apps. :param request: Django request. :return: Subset of app like objects that are listed in the settings `DASHBOARD_FEATURED_APPS` setting.
f4695:m1
def _remove_app_models(all_apps, models_to_remove):
filtered_apps = []<EOL>for app in all_apps:<EOL><INDENT>models = [x for x in app['<STR_LIT>'] if x not in models_to_remove]<EOL>if models:<EOL><INDENT>app['<STR_LIT>'] = models<EOL>filtered_apps.append(app)<EOL><DEDENT><DEDENT>return filtered_apps<EOL>
Remove the model specs in models_to_remove from the models specs in the apps in all_apps. If an app has no models left, don't include it in the output. This has the side-effect that the app view e.g. /admin/app/ may not be accessible from the dashboard, only the breadcrumbs.
f4695:m2
@register.filter<EOL>def filter_sorted_apps(admin_apps, request):
sorted_apps = []<EOL>for orig_app_spec in appsettings.DASHBOARD_SORTED_APPS:<EOL><INDENT>app_spec = orig_app_spec.copy()<EOL>app_spec['<STR_LIT>'] = _build_app_models(<EOL>request, admin_apps, app_spec['<STR_LIT>'], ensure_all_models=True<EOL>)<EOL>if app_spec['<STR_LIT>']:<EOL><INDENT>sorted_apps.append(app_spec)<EOL><DEDENT><DEDENT>used_models = []<EOL>for app in sorted_apps:<EOL><INDENT>used_models += app['<STR_LIT>']<EOL><DEDENT>sorted_apps += _remove_app_models(admin_apps, used_models)<EOL>return sorted_apps<EOL>
Filter admin_apps to show the ones in ``DASHBOARD_SORTED_APPS`` first, and remove them from the subsequent listings.
f4695:m3
@register.filter<EOL>def partition_app_list(app_list, n):
num_rows = sum([<NUM_LIT:1> + len(x['<STR_LIT>']) for x in app_list]) <EOL>num_rows_per_partition = num_rows / n<EOL>result = [[] for i in range(n)] <EOL>partition = <NUM_LIT:0><EOL>count = <NUM_LIT:0><EOL>for a in app_list:<EOL><INDENT>c = len(a['<STR_LIT>']) + <NUM_LIT:1> <EOL>if (partition < n - <NUM_LIT:1>) and (count + c/<NUM_LIT> > num_rows_per_partition):<EOL><INDENT>partition += <NUM_LIT:1><EOL>count = <NUM_LIT:0><EOL><DEDENT>result[partition].append(a)<EOL>count += c<EOL><DEDENT>return result<EOL>
:param app_list: A list of apps with models. :param n: Number of buckets to divide into. :return: Partition apps into n partitions, where the number of models in each list is roughly equal. We also factor in the app heading.
f4695:m4
def get_users(self, email):
<EOL>if hasattr(super(PasswordResetForm, self), '<STR_LIT>'):<EOL><INDENT>return (<EOL>u for u in super(PasswordResetForm, self).get_users(email)<EOL>if u.is_staff and u.is_active<EOL>)<EOL><DEDENT>active_users = get_user_model()._default_manager.filter(email__iexact=email, is_active=True)<EOL>return (u for u in active_users if u.has_usable_password() and u.is_staff and u.is_active)<EOL>
Make sure users are staff users. Additionally to the other PasswordResetForm conditions ensure that the user is a staff user before sending them a password reset email. :param email: Textual email address. :return: List of users.
f4697:c0:m0
def quote(key, value):
if key in quoted_options and isinstance(value, string_types):<EOL><INDENT>return "<STR_LIT>" % value<EOL><DEDENT>if key in quoted_bool_options and isinstance(value, bool):<EOL><INDENT>return {True:'<STR_LIT:true>',False:'<STR_LIT:false>'}[value]<EOL><DEDENT>return value<EOL>
Certain options support string values. We want clients to be able to pass Python strings in but we need them to be quoted in the output. Unfortunately some of those options also allow numbers so we type check the value before wrapping it in quotes.
f4700:m0
def child_type_name(self, inst):
return capfirst(inst.polymorphic_ctype.name)<EOL>
e.g. for use in list_display :param inst: a polymorphic parent instance :return: The name of the polymorphic model
f4701:c0:m0
def get_child_type_choices(self, request, action):
<EOL>choices = super(ChildModelPluginPolymorphicParentModelAdmin, self).get_child_type_choices(request, action)<EOL>plugins = self.child_model_plugin_class.get_plugins()<EOL>labels = {}<EOL>sort_priorities = {}<EOL>if plugins:<EOL><INDENT>for plugin in plugins:<EOL><INDENT>pk = plugin.content_type.pk<EOL>labels[pk] = capfirst(plugin.verbose_name)<EOL>sort_priorities[pk] = getattr(plugin, '<STR_LIT>', labels[pk])<EOL><DEDENT>choices = [(ctype, labels[ctype]) for ctype, _ in choices]<EOL>return sorted(choices,<EOL>cmp=lambda a, b: cmp(<EOL>sort_priorities[a[<NUM_LIT:0>]],<EOL>sort_priorities[b[<NUM_LIT:0>]]<EOL>)<EOL>)<EOL><DEDENT>return choices<EOL>
Override choice labels with ``verbose_name`` from plugins and sort.
f4701:c1:m0
def get_child_models(self):
child_models = []<EOL>for plugin in self.child_model_plugin_class.get_plugins():<EOL><INDENT>child_models.append((plugin.model, plugin.model_admin))<EOL><DEDENT>if not child_models:<EOL><INDENT>child_models.append((<EOL>self.child_model_admin.base_model,<EOL>self.child_model_admin,<EOL>))<EOL><DEDENT>return child_models<EOL>
Get child models from registered plugins. Fallback to the child model admin and its base model if no plugins are registered.
f4701:c1:m1
def _get_child_admin_site(self, rel):
if rel.to not in self.admin_site._registry:<EOL><INDENT>for parent in rel.to.mro():<EOL><INDENT>if parent in self.admin_site._registryand hasattr(self.admin_site._registry[parent], '<STR_LIT>'):<EOL><INDENT>return self.admin_site._registry[parent]._child_admin_site<EOL><DEDENT><DEDENT><DEDENT>return self.admin_site<EOL>
Returns the separate AdminSite instance that django-polymorphic maintains for child models. This admin site needs to be passed to the widget so that it passes the check of whether the field is pointing to a model that's registered in the admin. The hackiness of this implementation reflects the hackiness of the way django-polymorphic does things.
f4701:c2:m0
def formfield_for_foreignkey(self, db_field, request=None, **kwargs):
db = kwargs.get('<STR_LIT>')<EOL>if db_field.name in self.raw_id_fields:<EOL><INDENT>kwargs['<STR_LIT>'] = PolymorphicForeignKeyRawIdWidget(<EOL>db_field.rel,<EOL>admin_site=self._get_child_admin_site(db_field.rel),<EOL>using=db<EOL>)<EOL>if '<STR_LIT>' not in kwargs:<EOL><INDENT>queryset = self.get_field_queryset(db, db_field, request)<EOL>if queryset is not None:<EOL><INDENT>kwargs['<STR_LIT>'] = queryset<EOL><DEDENT><DEDENT>return db_field.formfield(**kwargs)<EOL><DEDENT>return super(PolymorphicAdminRawIdFix, self).formfield_for_foreignkey(<EOL>db_field, request=request, **kwargs)<EOL>
Replicates the logic in ModelAdmin.forfield_for_foreignkey, replacing the widget with the patched one above, initialising it with the child admin site.
f4701:c2:m1
def formfield_for_manytomany(self, db_field, request=None, **kwargs):
db = kwargs.get('<STR_LIT>')<EOL>if db_field.name in self.raw_id_fields:<EOL><INDENT>kwargs['<STR_LIT>'] = PolymorphicManyToManyRawIdWidget(<EOL>db_field.rel,<EOL>admin_site=self._get_child_admin_site(db_field.rel),<EOL>using=db<EOL>)<EOL>kwargs['<STR_LIT>'] = '<STR_LIT>'<EOL>if '<STR_LIT>' not in kwargs:<EOL><INDENT>queryset = self.get_field_queryset(db, db_field, request)<EOL>if queryset is not None:<EOL><INDENT>kwargs['<STR_LIT>'] = queryset<EOL><DEDENT><DEDENT>return db_field.formfield(**kwargs)<EOL><DEDENT>return super(PolymorphicAdminRawIdFix, self).formfield_for_manytomany(<EOL>db_field, request=request, **kwargs)<EOL>
Replicates the logic in ModelAdmin.formfield_for_manytomany, replacing the widget with the patched one above, initialising it with the child admin site.
f4701:c2:m2
def render_field_default(self, obj, request):
return unicode(obj)<EOL>
Default rendering for fields without `obj.preview()` or a custom `preview_<fieldname>`.
f4702:c0:m0
def render_field_error(self, obj_id, obj, exception, request):
if obj is None:<EOL><INDENT>msg = '<STR_LIT>'.format(obj_id)<EOL><DEDENT>else:<EOL><INDENT>msg = unicode(exception)<EOL><DEDENT>return u'<STR_LIT>'.format(msg)<EOL>
Default rendering for items in field where the the usual rendering method raised an exception.
f4702:c0:m1
def render_field_previews(self, id_and_obj_list, admin, request, field_name):
obj_preview_list = []<EOL>for obj_id, obj in id_and_obj_list:<EOL><INDENT>try:<EOL><INDENT>if obj is None:<EOL><INDENT>obj_preview = self.render_field_error(<EOL>obj_id, obj, None, request<EOL>)<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>obj_preview = admin.preview(obj, request)<EOL><DEDENT>except AttributeError:<EOL><INDENT>try:<EOL><INDENT>obj_preview = obj.preview(request)<EOL><DEDENT>except AttributeError:<EOL><INDENT>try:<EOL><INDENT>obj_preview = getattr(self, '<STR_LIT>'.format(<EOL>field_name))(obj, request)<EOL><DEDENT>except AttributeError:<EOL><INDENT>obj_preview = self.render_field_default(obj, request)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>obj_link = admin_link(obj, inner_html=obj_preview)<EOL><DEDENT>except Exception as ex:<EOL><INDENT>obj_link = self.render_field_error(obj_id, obj, ex, request)<EOL><DEDENT>obj_preview_list.append(obj_link)<EOL><DEDENT>li_html_list = [u'<STR_LIT>'.format(preview)<EOL>for preview in obj_preview_list]<EOL>if li_html_list:<EOL><INDENT>return u'<STR_LIT>'.format(u'<STR_LIT>'.join(li_html_list))<EOL><DEDENT>else:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>
Override this to customise the preview representation of all objects.
f4702:c0:m2
def admin_url(inst):
if inst:<EOL><INDENT>t = Template("""<STR_LIT>""")<EOL>return t.render(Context({ '<STR_LIT>': inst, '<STR_LIT>': inst._meta}))<EOL><DEDENT>return "<STR_LIT>"<EOL>
:param inst: An Model Instance :return: the admin URL for the instance. Permissions aren't checked.
f4703:m0
def admin_link(inst, attr_string="<STR_LIT>", inner_html="<STR_LIT>"):
<EOL>if inst:<EOL><INDENT>t = Template("""<STR_LIT>""")<EOL>return mark_safe(t.render(Context({ '<STR_LIT>': inst, '<STR_LIT>': inst._meta, '<STR_LIT>': attr_string, '<STR_LIT>': inner_html})))<EOL><DEDENT>return "<STR_LIT>"<EOL>
:param inst: An Model Instance :param attr_string: A string of attributes to be added to the <a> Tag. :param inner_html: Override html inside the <a> Tag. :return: a complete admin link for the instance. Permissions aren't checked.
f4703:m1
def get_unique_int(self):
try:<EOL><INDENT>self._unique_int += <NUM_LIT:1><EOL><DEDENT>except AttributeError:<EOL><INDENT>self._unique_int = <NUM_LIT:1><EOL><DEDENT>return self._unique_int<EOL>
Return a new auto-incremented integer value every time this method is called. This is useful where we need unique test data for things like writing new records with name or other values that must never match existing records.
f4707:c0:m2
def pp_data(self, data, indent=<NUM_LIT:4>):
print(json.dumps(data, indent=indent))<EOL>
Pretty-print data to stdout, to help debugging unit tests
f4707:c0:m3
def iso8601(self, dt):
if not is_aware(dt):<EOL><INDENT>dt = TZ.localize(dt)<EOL><DEDENT>return dt.astimezone(utc).replace(tzinfo=None).isoformat() + '<STR_LIT>'<EOL>
Return given datetime as UTC time in ISO 8601 format, cleaned up to use trailing 'Z' instead of rubbish like '+00:00'. Based on https://gist.github.com/bryanchow/1195854
f4707:c0:m4
def build_item_data(self, extend_data, base_data=None):
if base_data is None:<EOL><INDENT>base_data = dict(self.BASE_DATA)<EOL><DEDENT>for name, new_value in extend_data.items():<EOL><INDENT>if (<EOL>name in base_data and<EOL>isinstance(base_data[name], dict) and<EOL>isinstance(new_value, dict)<EOL>):<EOL><INDENT>self.build_item_data(extend_data[name], base_data[name])<EOL><DEDENT>else:<EOL><INDENT>base_data[name] = new_value<EOL><DEDENT><DEDENT>return base_data<EOL>
Populate a base data dict with new or overriden content
f4707:c0:m5
def listing_url(self):
return reverse('<STR_LIT>' % self.API_NAME)<EOL>
Return the listing URL endpoint for this class's API
f4707:c0:m6
def detail_url(self, id):
return reverse('<STR_LIT>' % self.API_NAME, args=[id])<EOL>
Return the detail URL endpoint for a given ID in this class's API
f4707:c0:m7
def client_apply_token(self, token):
self.client.credentials(HTTP_AUTHORIZATION='<STR_LIT>' + token.key)<EOL>
Apply the given token as token auth credentials for all follow-up requests from the client until reset by `self.client.credentials()`
f4707:c0:m8
def get_fields(self):
prefix = getattr(self.Meta, '<STR_LIT>', '<STR_LIT>')<EOL>fields = super(ModelSubSerializer, self).get_fields()<EOL>fields_without_prefix = OrderedDict()<EOL>for field_name, field in list(fields.items()):<EOL><INDENT>if field_name.startswith(prefix):<EOL><INDENT>if not field.source:<EOL><INDENT>field.source = field_name<EOL><DEDENT>field_name = field_name[len(prefix):]<EOL><DEDENT>fields_without_prefix[field_name] = field<EOL><DEDENT>return fields_without_prefix<EOL>
Convert default field names for this sub-serializer into versions where the field name has the prefix removed, but each field object knows the real model field name by setting the field's `source` attribute.
f4708:c0:m0
def _populate_validated_data_with_sub_field_data(self, validated_data):
for fieldname, field in list(self.get_fields().items()):<EOL><INDENT>if isinstance(field, ModelSubSerializer):<EOL><INDENT>field_data = validated_data.pop(fieldname, None)<EOL>if field_data:<EOL><INDENT>validated_data.update(field_data)<EOL><DEDENT><DEDENT><DEDENT>
Move field data nested in `ModelSubSerializer` fields back into the overall validated data dict.
f4708:c2:m0
def _prepare_related_single_or_m2m_relations(self, validated_data):
many_to_many_relationships = {}<EOL>for fieldname, field in list(self.get_fields().items()):<EOL><INDENT>if (<EOL>isinstance(field, ModelSubSerializer) or<EOL>field.read_only or<EOL>not (<EOL>isinstance(field, serializers.ModelSerializer) or<EOL>isinstance(field, serializers.ListSerializer)<EOL>)<EOL>):<EOL><INDENT>continue <EOL><DEDENT>is_list_field = isinstance(field, serializers.ListSerializer)<EOL>if is_list_field:<EOL><INDENT>ModelClass = field.child.Meta.model<EOL>field_data_list = validated_data.pop(fieldname, [])<EOL><DEDENT>else:<EOL><INDENT>ModelClass = field.Meta.model<EOL>field_data_list = validated_data.pop(fieldname, None)<EOL>field_data_list = field_data_list and [field_data_list] or []<EOL><DEDENT>if not field_data_list:<EOL><INDENT>continue<EOL><DEDENT>related_instances = []<EOL>for field_data in field_data_list:<EOL><INDENT>related_instance =self._get_or_update_or_create_related_instance(<EOL>ModelClass, fieldname, field_data)<EOL>if related_instance:<EOL><INDENT>related_instances.append(related_instance)<EOL><DEDENT><DEDENT>if not is_list_field:<EOL><INDENT>validated_data[fieldname] = related_instances[<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>many_to_many_relationships[fieldname] = related_instances<EOL><DEDENT><DEDENT>return many_to_many_relationships<EOL>
Handle writing to nested related model fields for both single and many-to-many relationships. For single relationships, any existing or new instance resulting from the provided data is set back into the provided `validated_data` to be applied by DjangoRestFramework's default handling. For M2M relationships, any existing or new instances resulting from the provided data are returned in a dictionary mapping M2M field names to a list of instances to be related. The actual relationship is then applied by `_write_related_m2m_relations` because DjangoRestFramework does not support assigning M2M fields.
f4708:c2:m1
def _get_or_update_or_create_related_instance(<EOL>self, ModelClass, fieldname, field_data<EOL>):
writable_related_fields = getattr(<EOL>self.Meta, '<STR_LIT>', {})<EOL>if fieldname not in writable_related_fields:<EOL><INDENT>raise TypeError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>% (fieldname, ModelClass.__name__,<EOL>self.Meta.model.__name__)<EOL>)<EOL><DEDENT>field_settings = writable_related_fields[fieldname]<EOL>if not isinstance(field_settings, WritableRelatedFieldSettings):<EOL><INDENT>raise TypeError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>% (fieldname, ModelClass.__name__, type(field_settings))<EOL>)<EOL><DEDENT>lookup_fields = field_settings.lookup_field<EOL>if not isinstance(lookup_fields, (list, tuple)):<EOL><INDENT>lookup_fields = [lookup_fields]<EOL><DEDENT>lookup_value = None<EOL>for lookup_field in lookup_fields:<EOL><INDENT>if lookup_field in field_data:<EOL><INDENT>lookup_value = field_data.pop(lookup_field)<EOL>break<EOL><DEDENT><DEDENT>if lookup_value is None and not field_settings.can_create:<EOL><INDENT>raise TypeError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>% (fieldname, ModelClass.__name__,<EOL>self.Meta.model.__name__, lookup_fields, field_data)<EOL>)<EOL><DEDENT>related_instance = None<EOL>try:<EOL><INDENT>related_instance = ModelClass.objects.get(<EOL>**{lookup_field: lookup_value})<EOL>is_updated = False<EOL>for name, value in list(field_data.items()):<EOL><INDENT>original_value = getattr(related_instance, name)<EOL>if value != original_value:<EOL><INDENT>if not field_settings.can_update:<EOL><INDENT>raise TypeError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>% (fieldname, ModelClass.__name__,<EOL>self.Meta.model.__name__, name, value,<EOL>original_value)<EOL>)<EOL><DEDENT>setattr(related_instance, name, value)<EOL>is_updated = True<EOL><DEDENT><DEDENT>if is_updated:<EOL><INDENT>related_instance.save()<EOL><DEDENT><DEDENT>except ModelClass.MultipleObjectsReturned as ex:<EOL><INDENT>raise TypeError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>% (fieldname, ModelClass.__name__,<EOL>self.Meta.model.__name__, lookup_field, lookup_value, ex)<EOL>)<EOL><DEDENT>except ModelClass.DoesNotExist:<EOL><INDENT>if not field_settings.can_create:<EOL><INDENT>raise TypeError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>% (fieldname, ModelClass.__name__,<EOL>self.Meta.model.__name__)<EOL>)<EOL><DEDENT>field_data.update({lookup_field: lookup_value})<EOL>related_instance = ModelClass.objects.create(**field_data)<EOL><DEDENT>return related_instance<EOL>
Handle lookup, update, or creation of related instances based on the field data provided and the field's `writable_related_fields` settings as defined on the serializer's `Meta`. This method will: - fail immediately if the field does not have `writable_related_fields` settings defined, or if these settings are not valid `WritableRelatedFieldSettings` objects - look up an existing instance using the defined `lookup_field` if a value is provided for the lookup field: - if no lookup field value is provided, fail unless `can_create` is set on the field since we cannot find any existing instance - if no existing instance is found, fail unless `can_create` - find the matching existing instance - if there is an existing instance: - if other data is provided, fail unless `can_update` is set - update existing instance based on other data provided if `can_update is set` - return the existing instance - if there is not an existing instance and `can_create` is set: - create a new instance with provided data - return the new instance
f4708:c2:m2
def _write_related_m2m_relations(self, obj, many_to_many_relationships):
for fieldname, related_objs in list(many_to_many_relationships.items()):<EOL><INDENT>setattr(obj, fieldname, related_objs)<EOL><DEDENT>
For the given `many_to_many_relationships` dict mapping field names to a list of object instances, apply the instance listing to the `obj`s named many-to-many relationship field.
f4708:c2:m3
def retrieve(self, request, *args, **kwargs):
try:<EOL><INDENT>instance = self.get_object()<EOL>serializer = self.get_serializer(instance)<EOL>return Response(serializer.data)<EOL><DEDENT>except Http404:<EOL><INDENT>pass<EOL><DEDENT>lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field<EOL>slug = self.kwargs[lookup_url_kwarg]<EOL>try:<EOL><INDENT>tmp = get_object_or_404(<EOL>self.queryset, accession_temp_fallback=slug)<EOL>return HttpResponseRedirect(<EOL>reverse(self.redirect_view_name, (tmp.slug, ))<EOL>)<EOL><DEDENT>except (Http404, FieldError):<EOL><INDENT>pass<EOL><DEDENT>try:<EOL><INDENT>embark = get_object_or_404(self.queryset, id=int(slug))<EOL>return HttpResponseRedirect(<EOL>reverse(self.redirect_view_name, (embark.slug, ))<EOL>)<EOL><DEDENT>except (Http404, ValueError):<EOL><INDENT>pass<EOL><DEDENT>try:<EOL><INDENT>from glamkit_collections.utils import alt_slugify<EOL>alt_slug = alt_slugify(slug)<EOL>alt = get_object_or_404(self.queryset, alt_slug=alt_slug)<EOL>return HttpResponseRedirect(<EOL>reverse(self.redirect_view_name, (alt.slug, ))<EOL>)<EOL><DEDENT>except Http404:<EOL><INDENT>pass<EOL><DEDENT>raise Http404<EOL>
If the URL slug doesn't match an object, try slugifying the URL param and searching alt_url for that. If found, redirect to the canonical URL. If still not found, raise 404.
f4712:c1:m0
def get_content(self, obj):
serializer = ContentSerializer(<EOL>instance=obj.contentitem_set.all(),<EOL>many=True,<EOL>context=self.context,<EOL>)<EOL>return serializer.data<EOL>
Obtain the QuerySet of content items. :param obj: Page object. :return: List of rendered content items.
f4720:c1:m0
def dump_viewset(viewset_class, root_folder, folder_fn=lambda i: "<STR_LIT:.>", sample_size=None):
if os.path.exists(root_folder):<EOL><INDENT>shutil.rmtree(root_folder)<EOL><DEDENT>os.makedirs(root_folder)<EOL>vs = viewset_class()<EOL>vs.request = rf.get('<STR_LIT>')<EOL>serializer_class = vs.get_serializer_class()<EOL>serializer = serializer_class(context={'<STR_LIT>': vs.request, '<STR_LIT>': '<STR_LIT>', '<STR_LIT>': vs})<EOL>renderer = PrettyJSONRenderer()<EOL>bar = progressbar.ProgressBar()<EOL>for instance in bar(vs.get_queryset()[:sample_size]):<EOL><INDENT>dct = serializer.to_representation(instance)<EOL>content = renderer.render(dct)<EOL>folder = os.path.join(root_folder, folder_fn(instance))<EOL>if not os.path.exists(folder):<EOL><INDENT>os.makedirs(folder)<EOL><DEDENT>filename = "<STR_LIT>" % instance.slug<EOL>f = file(os.path.join(folder, filename), '<STR_LIT:w>')<EOL>f.write(content)<EOL>f.close()<EOL><DEDENT>
Dump the contents of a rest-api queryset to a folder structure. :param viewset_class: A rest-api viewset to iterate through :param root_folder: The root folder to write results to. :param folder_fn: A function to generate a subfolder name for the instance. :param sample_size: Number of items to process, for test purposes. :return:
f4725:m1
def concatenate_json(source_folder, destination_file):
matches = []<EOL>for root, dirnames, filenames in os.walk(source_folder):<EOL><INDENT>for filename in fnmatch.filter(filenames, '<STR_LIT>'):<EOL><INDENT>matches.append(os.path.join(root, filename))<EOL><DEDENT><DEDENT>with open(destination_file, "<STR_LIT:wb>") as f:<EOL><INDENT>f.write("<STR_LIT>")<EOL>for m in matches[:-<NUM_LIT:1>]:<EOL><INDENT>f.write(open(m, "<STR_LIT:rb>").read())<EOL>f.write("<STR_LIT>")<EOL><DEDENT>f.write(open(matches[-<NUM_LIT:1>], "<STR_LIT:rb>").read())<EOL>f.write("<STR_LIT>")<EOL><DEDENT>
Concatenate all the json files in a folder to one big JSON file.
f4725:m2
def get_items_to_list(self, request=None):
return Author.objects.published()<EOL>
:return: all published authors
f4782:c0:m0
def get_items_to_mount(self, request):
return Author.objects.visible()<EOL>
:return: all authors that can be viewed by the current user
f4782:c0:m1
@property<EOL><INDENT>def url_link_text(self):<DEDENT>
url_link_text = re.sub('<STR_LIT>', '<STR_LIT>', self.url)<EOL>return url_link_text.strip('<STR_LIT:/>')<EOL>
Return a cleaned-up version of the URL of an author's website, to use as a label for a link. TODO: make a template filter :return: String.
f4782:c1:m2
def contributions(self):
return []<EOL>
:return: List of all content that should show for this author.
f4782:c1:m3
def contributions(self):
draft = self.get_draft()<EOL>links = AuthorLink.objects.filter(item_id=draft.id, exclude_from_contributions=False)<EOL>default_time = now()<EOL>def _key(x):<EOL><INDENT>return getattr(x, '<STR_LIT>',<EOL>getattr(x, '<STR_LIT>',<EOL>default_time)) or default_time<EOL><DEDENT>return sorted([x.parent for x in links if x.parent.is_visible], key=_key)<EOL>
:return: All content that has a link to the (draft) author.
f4782:c1:m7
def one_instance(function=None, key='<STR_LIT>', timeout=DEFAULT_ONE_INSTANCE_TIMEOUT):
def _dec(run_func):<EOL><INDENT>def _caller(*args, **kwargs):<EOL><INDENT>ret_value = None<EOL>have_lock = False<EOL>if REDIS_CLIENT.config_get('<STR_LIT>').values()[<NUM_LIT:0>] == '<STR_LIT>':<EOL><INDENT>REDIS_CLIENT.config_set('<STR_LIT>', '<STR_LIT:yes>')<EOL><DEDENT>lock = REDIS_CLIENT.lock(key, timeout=timeout)<EOL>try:<EOL><INDENT>logger.debug(<EOL>'<STR_LIT>'<EOL>% (key, os.getpid()))<EOL>have_lock = lock.acquire(blocking=False)<EOL>if have_lock:<EOL><INDENT>logger.debug(<EOL>'<STR_LIT>' % (key, os.getpid()))<EOL>ret_value = run_func(*args, **kwargs)<EOL><DEDENT>else:<EOL><INDENT>logger.error(<EOL>'<STR_LIT>'<EOL>% (key, os.getpid()))<EOL><DEDENT><DEDENT>finally:<EOL><INDENT>if have_lock:<EOL><INDENT>lock.release()<EOL>logger.debug(<EOL>'<STR_LIT>' % (key, os.getpid()))<EOL><DEDENT><DEDENT>return ret_value<EOL><DEDENT>return _caller<EOL><DEDENT>return _dec(function) if function is not None else _dec<EOL>
Decorator to enforce only one Celery task execution at a time when multiple workers are available. See http://loose-bits.com/2010/10/distributed-task-locking-in-celery.html
f4792:m0
def handle_noargs(self, **options):
is_dry_run = options.get('<STR_LIT>', False)<EOL>mptt_only = options.get('<STR_LIT>', False)<EOL>slugs = {}<EOL>overrides = {}<EOL>parents = dict(<EOL>UrlNode.objects.filter(status=UrlNode.DRAFT).values_list('<STR_LIT:id>', '<STR_LIT>')<EOL>)<EOL>self.stdout.write("<STR_LIT>")<EOL>if is_dry_run and mptt_only:<EOL><INDENT>return<EOL><DEDENT>if not is_dry_run:<EOL><INDENT>opts = UrlNode._mptt_meta<EOL>qs = UrlNode.objects._mptt_filter(<EOL>qs=UrlNode.objects.filter(status=UrlNode.DRAFT),<EOL>parent=None<EOL>)<EOL>if opts.order_insertion_by:<EOL><INDENT>qs = qs.order_by(*opts.order_insertion_by)<EOL><DEDENT>pks = qs.values_list('<STR_LIT>', flat=True)<EOL>rebuild_helper = UrlNode.objects._rebuild_helper<EOL>idx = <NUM_LIT:0><EOL>for pk in pks:<EOL><INDENT>idx += <NUM_LIT:1><EOL>rebuild_helper(pk, <NUM_LIT:1>, idx)<EOL><DEDENT>self.stdout.write("<STR_LIT>")<EOL>if mptt_only:<EOL><INDENT>return<EOL><DEDENT>self.stdout.write("<STR_LIT>")<EOL>self.stdout.write("<STR_LIT>")<EOL><DEDENT>col_style = u"<STR_LIT>"<EOL>header = col_style.format("<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>")<EOL>sep = '<STR_LIT:->' * (len(header) + <NUM_LIT>)<EOL>self.stdout.write(sep)<EOL>self.stdout.write(header)<EOL>self.stdout.write(sep)<EOL>for translation in UrlNode_Translation.objects.filter(<EOL>master__status=UrlNode.DRAFT<EOL>).select_related('<STR_LIT>').order_by(<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>'<EOL>):<EOL><INDENT>slugs.setdefault(translation.language_code, {})[translation.master_id] = translation.slug<EOL>overrides.setdefault(translation.language_code, {})[translation.master_id] = translation.override_url<EOL>old_url = translation._cached_url<EOL>try:<EOL><INDENT>new_url = self._construct_url(translation.language_code, translation.master_id, parents, slugs, overrides)<EOL><DEDENT>except KeyError:<EOL><INDENT>if is_dry_run:<EOL><INDENT>self.stderr.write("<STR_LIT>".format(old_url))<EOL>return<EOL><DEDENT>raise<EOL><DEDENT>if old_url != new_url:<EOL><INDENT>translation._cached_url = new_url<EOL>if not is_dry_run:<EOL><INDENT>translation.save()<EOL><DEDENT><DEDENT>if old_url != new_url:<EOL><INDENT>self.stdout.write(smart_text(u"<STR_LIT>".format(<EOL>col_style.format(translation.master.parent_site_id, translation.master_id, translation.language_code, translation._cached_url),<EOL>"<STR_LIT>" if is_dry_run else "<STR_LIT>",<EOL>old_url<EOL>)))<EOL><DEDENT>else:<EOL><INDENT>self.stdout.write(smart_text(col_style.format(<EOL>translation.master.parent_site_id, translation.master_id, translation.language_code, translation._cached_url<EOL>)))<EOL><DEDENT><DEDENT>
By default this function runs on all objects. As we are using a publishing system it should only update draft objects which can be modified in the tree structure. Once published the tree preferences should remain the same to ensure the tree data structure is consistent with what was published by the user.
f4794:c0:m0
def find_existing_page(self, titles_hierarchy):
<EOL>titles_filters = {'<STR_LIT>': True}<EOL>for parent_count, ancestor_titlein enumerate(titles_hierarchy[::-<NUM_LIT:1>]):<EOL><INDENT>parent_path = '<STR_LIT>'.join(['<STR_LIT>'] * parent_count)<EOL>filter_name = '<STR_LIT>' % (<EOL>parent_path, parent_path and '<STR_LIT>' or '<STR_LIT>')<EOL>titles_filters[filter_name] = ancestor_title<EOL><DEDENT>return self.page_model.objects.filter(**titles_filters).first()<EOL>
Find and return existing page matching the given titles hierarchy
f4800:c0:m1
def save(self, *args, **kwargs):
self.modified = timezone.now()<EOL>super(AbstractBaseModel, self).save(*args, **kwargs)<EOL>
Update ``self.modified``.
f4802:c0:m0
@classmethod<EOL><INDENT>def auto_add(cls, template_name, *models, **kwargs):<DEDENT>
separator = kwargs.get('<STR_LIT>', '<STR_LIT:U+002CU+0020>')<EOL>content_types = ContentType.objects.get_for_models(*models).values()<EOL>try:<EOL><INDENT>layout = cls.objects.get(template_name=template_name)<EOL><DEDENT>except cls.DoesNotExist:<EOL><INDENT>title = separator.join(sorted(<EOL>ct.model_class()._meta.verbose_name for ct in content_types))<EOL>layout = cls.objects.create(<EOL>template_name=template_name,<EOL>title=title,<EOL>)<EOL>layout.content_types.add(*content_types)<EOL><DEDENT>else:<EOL><INDENT>title = [layout.title]<EOL>for ct in content_types:<EOL><INDENT>if not layout.content_types.filter(pk=ct.pk).exists():<EOL><INDENT>title.append(ct.model_class()._meta.verbose_name)<EOL><DEDENT><DEDENT>layout.title = separator.join(sorted(title))<EOL>layout.save()<EOL>layout.content_types.add(*content_types)<EOL><DEDENT>return layout<EOL>
Get or create a layout for the given template and add content types for the given models to it. Append the verbose name of each model to the title with the given ``separator`` keyword argument.
f4802:c1:m1
def get_placeholder_data(self):
return get_template_placeholder_data(self.get_template())<EOL>
Return placeholder data for this layout's template.
f4802:c1:m2
def get_template(self):
return get_template(self.template_name)<EOL>
Return the template to render this layout.
f4802:c1:m3
def environment(**options):
env = Environment(**options)<EOL>env.globals.update({<EOL>'<STR_LIT>': staticfiles_storage.url,<EOL>'<STR_LIT:url>': reverse,<EOL>})<EOL>env.globals.update(context_processors.environment())<EOL>return env<EOL>
Add ``static`` and ``url`` functions to the ``environment`` context processor and return as a Jinja2 ``Environment`` object.
f4803:m0
def environment(request=None):
context = {<EOL>'<STR_LIT>': settings.COMPRESS_ENABLED,<EOL>'<STR_LIT>': settings.SITE_NAME,<EOL>}<EOL>for key in settings.ICEKIT_CONTEXT_PROCESSOR_SETTINGS:<EOL><INDENT>context[key] = getattr(settings, key, None)<EOL><DEDENT>return context<EOL>
Return ``COMPRESS_ENABLED``, ``SITE_NAME``, and any settings listed in ``ICEKIT_CONTEXT_PROCESSOR_SETTINGS`` as context.
f4808:m0
def index_queryset(self, using=None):
translation.activate(settings.LANGUAGE_CODE)<EOL>return self.get_model().objects.filter(status=UrlNode.PUBLISHED).select_related()<EOL>
Index current language translation of published objects. TODO: Find a way to index all translations of the given model, not just the current site language's translation.
f4820:c0:m1
def get_response_page(request, return_type, template_location, response_page_type):
try:<EOL><INDENT>page = models.ResponsePage.objects.get(<EOL>is_active=True,<EOL>type=response_page_type,<EOL>)<EOL>template = loader.get_template(template_location)<EOL>content_type = None<EOL>body = template.render(<EOL>RequestContext(request, {'<STR_LIT>': request.path, '<STR_LIT>': page, })<EOL>)<EOL>return return_type(body, content_type=content_type)<EOL><DEDENT>except models.ResponsePage.DoesNotExist:<EOL><INDENT>return None<EOL><DEDENT>
Helper function to get an appropriate response page if it exists. This function is not designed to be used directly as a view. It is a helper function which can be called to check if a ResponsePage exists for a ResponsePage type (which is also active). :param request: :param return_type: :param template_location: :param response_page_type: :return:
f4824:m0
@requires_csrf_token<EOL>def page_not_found(request, template_name='<STR_LIT>'):
rendered_page = get_response_page(<EOL>request,<EOL>http.HttpResponseNotFound,<EOL>'<STR_LIT>',<EOL>abstract_models.RESPONSE_HTTP404<EOL>)<EOL>if rendered_page is None:<EOL><INDENT>return defaults.page_not_found(request, template_name)<EOL><DEDENT>return rendered_page<EOL>
Custom page not found (404) handler. Don't raise a Http404 or anything like that in here otherwise you will cause an infinite loop. That would be bad. If no ResponsePage exists for with type ``RESPONSE_HTTP404`` then the default template render view will be used. Templates: :template:`404.html` Context: request_path The path of the requested URL (e.g., '/app/pages/bad_page/') page A ResponsePage with type ``RESPONSE_HTTP404`` if it exists.
f4824:m1
@requires_csrf_token<EOL>def server_error(request, template_name='<STR_LIT>'):
try:<EOL><INDENT>rendered_page = get_response_page(<EOL>request,<EOL>http.HttpResponseServerError,<EOL>'<STR_LIT>',<EOL>abstract_models.RESPONSE_HTTP500<EOL>)<EOL>if rendered_page is not None:<EOL><INDENT>return rendered_page<EOL><DEDENT><DEDENT>except Exception:<EOL><INDENT>pass<EOL><DEDENT>return defaults.server_error(request, template_name)<EOL>
Custom 500 error handler. The exception clause is so broad to capture any 500 errors that may have been generated from getting the response page e.g. if the database was down. If they were not handled they would cause a 500 themselves and form an infinite loop. If no ResponsePage exists for with type ``RESPONSE_HTTP500`` then the default template render view will be used. Templates: :template:`500.html` Context: page A ResponsePage with type ``RESPONSE_HTTP500`` if it exists.
f4824:m2
def lookups(self, request, model_admin):
types = models.EventType.objects.filter(is_public=True).order_by('<STR_LIT>')<EOL>types = [(t.id, t.swatch()) for t in types]<EOL>return types<EOL>
Returns a list of tuples. The first element in each tuple is the coded value for the option that will appear in the URL query. The second element is the human-readable name for the option that will appear in the right sidebar.
f4842:c5:m0
def get_urls(self):
from django.conf.urls import patterns, url<EOL>urls = super(EventAdmin, self).get_urls()<EOL>my_urls = patterns(<EOL>'<STR_LIT>',<EOL>url(<EOL>r'<STR_LIT>',<EOL>self.admin_site.admin_view(self.calendar),<EOL>name='<STR_LIT>'<EOL>),<EOL>url(<EOL>r'<STR_LIT>',<EOL>self.admin_site.admin_view(self.calendar_data),<EOL>name='<STR_LIT>'<EOL>),<EOL>)<EOL>return my_urls + urls<EOL>
Add a calendar URL.
f4842:c6:m5
def calendar(self, request):
context = {<EOL>'<STR_LIT>': bool(int(request.GET.get('<STR_LIT>', <NUM_LIT:0>))),<EOL>}<EOL>return TemplateResponse(<EOL>request, '<STR_LIT>', context)<EOL>
Return a calendar page to be loaded in an iframe.
f4842:c6:m6
def calendar_data(self, request):
<EOL>request.GET = request.GET.copy()<EOL>if '<STR_LIT>' in request.GET:<EOL><INDENT>tz = djtz.get(request.GET.pop('<STR_LIT>'))<EOL><DEDENT>else:<EOL><INDENT>tz = get_current_timezone()<EOL><DEDENT>if '<STR_LIT:start>' in request.GET:<EOL><INDENT>start_dt = self._parse_dt_from_request(request, '<STR_LIT:start>')<EOL>if start_dt:<EOL><INDENT>start = djtz.localize(start_dt, tz)<EOL><DEDENT>else:<EOL><INDENT>start = None<EOL><DEDENT><DEDENT>else:<EOL><INDENT>start = None<EOL><DEDENT>if '<STR_LIT:end>' in request.GET:<EOL><INDENT>end_dt = self._parse_dt_from_request(request, '<STR_LIT:end>')<EOL>if end_dt:<EOL><INDENT>end = djtz.localize(end_dt, tz)<EOL><DEDENT>else:<EOL><INDENT>end = None<EOL><DEDENT><DEDENT>else:<EOL><INDENT>end = None<EOL><DEDENT>cl = ChangeList(request, self.model, self.list_display,<EOL>self.list_display_links, self.list_filter,<EOL>self.date_hierarchy, self.search_fields,<EOL>self.list_select_related, self.list_per_page,<EOL>self.list_max_show_all, self.list_editable, self)<EOL>filtered_event_ids = cl.get_queryset(request).values_list('<STR_LIT:id>', flat=True)<EOL>all_occurrences = models.Occurrence.objects.filter(event__id__in=filtered_event_ids).overlapping(start, end)<EOL>data = []<EOL>for occurrence in all_occurrences.all():<EOL><INDENT>data.append(self._calendar_json_for_occurrence(occurrence))<EOL><DEDENT>data = json.dumps(data, cls=DjangoJSONEncoder)<EOL>return HttpResponse(content=data, content_type='<STR_LIT:application/json>')<EOL>
Return event data in JSON format for AJAX requests, or a calendar page to be loaded in an iframe.
f4842:c6:m7
def _calendar_json_for_occurrence(self, occurrence):
<EOL>if occurrence.is_all_day:<EOL><INDENT>start = occurrence.start<EOL>end = occurrence.start + timedelta(days=<NUM_LIT:1>)<EOL><DEDENT>else:<EOL><INDENT>start = djtz.localize(occurrence.start)<EOL>end = djtz.localize(occurrence.end)<EOL><DEDENT>if occurrence.is_cancelled and occurrence.cancel_reason:<EOL><INDENT>title = u"<STR_LIT>".format(<EOL>occurrence.event.title, occurrence.cancel_reason)<EOL><DEDENT>else:<EOL><INDENT>title = occurrence.event.title<EOL><DEDENT>if occurrence.event.primary_type:<EOL><INDENT>color = occurrence.event.primary_type.color<EOL><DEDENT>else:<EOL><INDENT>color = "<STR_LIT>"<EOL><DEDENT>return {<EOL>'<STR_LIT:title>': title,<EOL>'<STR_LIT>': occurrence.is_all_day or occurrence.event.contained_events.exists(),<EOL>'<STR_LIT:start>': start,<EOL>'<STR_LIT:end>': end,<EOL>'<STR_LIT:url>': reverse('<STR_LIT>',<EOL>args=[occurrence.event.pk]),<EOL>'<STR_LIT>': self._calendar_classes_for_occurrence(occurrence),<EOL>'<STR_LIT>': color,<EOL>}<EOL>
Return JSON for a single Occurrence
f4842:c6:m9
def _calendar_classes_for_occurrence(self, occurrence):
classes = [slugify(occurrence.event.polymorphic_ctype.name)]<EOL>if occurrence.is_all_day:<EOL><INDENT>classes.append('<STR_LIT>')<EOL><DEDENT>if occurrence.is_protected_from_regeneration:<EOL><INDENT>classes.append('<STR_LIT>')<EOL><DEDENT>if occurrence.is_cancelled:<EOL><INDENT>classes.append('<STR_LIT>')<EOL><DEDENT>if not occurrence.event.show_in_calendar:<EOL><INDENT>classes.append('<STR_LIT>')<EOL><DEDENT>classes = ['<STR_LIT>' % class_ for class_ in classes]<EOL>return classes<EOL>
Return css classes to be used in admin calendar JSON
f4842:c6:m10
def get_urls(self):
from django.conf.urls import patterns, url<EOL>urls = super(RecurrenceRuleAdmin, self).get_urls()<EOL>my_urls = patterns(<EOL>'<STR_LIT>',<EOL>url(<EOL>r'<STR_LIT>',<EOL>self.admin_site.admin_view(self.preview),<EOL>name='<STR_LIT>'<EOL>),<EOL>)<EOL>return my_urls + urls<EOL>
Add a preview URL.
f4842:c8:m0
@csrf_exempt<EOL><INDENT>def preview(self, request):<DEDENT>
recurrence_rule = request.POST.get('<STR_LIT>')<EOL>limit = int(request.POST.get('<STR_LIT>', <NUM_LIT:10>))<EOL>try:<EOL><INDENT>rruleset = rrule.rrulestr(<EOL>recurrence_rule, dtstart=djtz.now(), forceset=True)<EOL><DEDENT>except ValueError as e:<EOL><INDENT>data = {<EOL>'<STR_LIT:error>': six.text_type(e),<EOL>}<EOL><DEDENT>else:<EOL><INDENT>data = {<EOL>'<STR_LIT>': rruleset[:limit]<EOL>}<EOL><DEDENT>return JsonResponse(data)<EOL>
Return a occurrences in JSON format up until the configured limit.
f4842:c8:m1
def setUp(self):
self.start = timeutils.round_datetime(<EOL>when=djtz.now(),<EOL>precision=timedelta(days=<NUM_LIT:1>),<EOL>rounding=timeutils.ROUND_DOWN)<EOL>self.end = self.start + appsettings.DEFAULT_ENDS_DELTA<EOL>self.naive_start = coerce_naive(self.start)<EOL>self.naive_end = coerce_naive(self.end)<EOL>
Create a daily recurring event with no end date
f4844:c6:m0
def setUp(self):
self.start = timeutils.round_datetime(<EOL>when=djtz.now(),<EOL>precision=timedelta(days=<NUM_LIT:1>),<EOL>rounding=timeutils.ROUND_DOWN)<EOL>self.end = self.start + appsettings.DEFAULT_ENDS_DELTA<EOL>
Create an event with a daily repeat generator.
f4844:c7:m0
@register.filter<EOL>def timesf(times_list, format=None):
return [time(t, format) for t in times_list]<EOL>
:param times_list: the list of times to format :param format: the format to apply (default = settings.TIME_FORMAT) :return: the times, formatted according to the format
f4845:m0
def _format_with_same_year(format_specifier):
<EOL>test_format_specifier = format_specifier + "<STR_LIT>"<EOL>test_format = get_format(test_format_specifier, use_l10n=True)<EOL>if test_format == test_format_specifier:<EOL><INDENT>return re.sub(YEAR_RE, '<STR_LIT>', get_format(format_specifier))<EOL><DEDENT>else:<EOL><INDENT>return test_format<EOL><DEDENT>
Return a version of `format_specifier` that renders a date assuming it has the same year as another date. Usually this means ommitting the year. This can be overridden by specifying a format that has `_SAME_YEAR` appended to the name in the project's `formats` spec.
f4845:m3
def _format_with_same_year_and_month(format_specifier):
test_format_specifier = format_specifier + "<STR_LIT>"<EOL>test_format = get_format(test_format_specifier, use_l10n=True)<EOL>if test_format == test_format_specifier:<EOL><INDENT>no_year = re.sub(YEAR_RE, '<STR_LIT>', get_format(format_specifier))<EOL>return re.sub(MONTH_RE, '<STR_LIT>', no_year)<EOL><DEDENT>else:<EOL><INDENT>return test_format<EOL><DEDENT>
Return a version of `format_specifier` that renders a date assuming it has the same year and month as another date. Usually this means ommitting the year and month. This can be overridden by specifying a format that has `_SAME_YEAR_SAME_MONTH` appended to the name in the project's `formats` spec.
f4845:m4
@register.filter(is_safe=True)<EOL>def dates_range(event, format="<STR_LIT>"):
<EOL>date_format = settings.DATE_FORMAT <EOL>separator = "<STR_LIT>"<EOL>no_dates_text = '<STR_LIT>'<EOL>from_text = "<STR_LIT>"<EOL>arg_list = [arg.strip() for arg in format.split('<STR_LIT:|>')]<EOL>if arg_list:<EOL><INDENT>date_format = arg_list[<NUM_LIT:0>]<EOL>try:<EOL><INDENT>separator = arg_list[<NUM_LIT:1>]<EOL>no_dates_text = arg_list[<NUM_LIT:2>]<EOL>from_text = arg_list[<NUM_LIT:3>]<EOL>ended_text = arg_list[<NUM_LIT:4>]<EOL><DEDENT>except IndexError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>if event.human_dates:<EOL><INDENT>return event.human_dates.strip()<EOL><DEDENT>first, last = event.get_occurrences_range()<EOL>start, end = None, None<EOL>if first:<EOL><INDENT>start = first.local_start<EOL><DEDENT>if last:<EOL><INDENT>end = last.local_end<EOL><DEDENT>if start and end:<EOL><INDENT>first_date_format = get_format(date_format, use_l10n=True)<EOL>if start.year == end.year:<EOL><INDENT>first_date_format = _format_with_same_year(date_format)<EOL>if start.month == end.month:<EOL><INDENT>first_date_format = _format_with_same_year_and_month(date_format)<EOL>if start.day == end.day:<EOL><INDENT>return mark_safe(datefilter(start, date_format))<EOL><DEDENT><DEDENT><DEDENT>return mark_safe('<STR_LIT>' % (<EOL>datefilter(start, first_date_format),<EOL>separator,<EOL>datefilter(end, date_format)<EOL>))<EOL><DEDENT>elif start and not end:<EOL><INDENT>return '<STR_LIT>' % (from_text, datefilter(start, date_format))<EOL><DEDENT>elif not (start or end):<EOL><INDENT>return no_dates_text<EOL><DEDENT>else:<EOL><INDENT>raise AssertionError("<STR_LIT>")<EOL><DEDENT>
:param event: An Event :param format: A |-separated string specifying: date_format - a format specifier separator - the string to join the start and end dates with, if they're different no_dates_text - text to return if the event has no occurrences, default '' from_text - text to prepend if the event never ends (the 'last' date is None) :return: text describing the date range for the event. If human dates are given, use that, otherwise, use the first and last occurrences for an event. If the first and last dates have year or year and month in common, the format string for the first date is modified to exclude those items. If the first and last dates are equal, only the first date is used (ie with no range) You can override this behaviour by specifying additional formats with "_SAME_YEAR" and "_SAME_YEAR_SAME_MONTH" appended to the name.
f4845:m5
def forwards_migration(apps, schema_editor):
RecurrenceRule = apps.get_model('<STR_LIT>', '<STR_LIT>')<EOL>for rrule in RecurrenceRule.objects.all():<EOL><INDENT>if '<STR_LIT>' in rrule.recurrence_rule:<EOL><INDENT>parts = rrule.recurrence_rule.split('<STR_LIT>')<EOL>rrule.recurrence_rule = '<STR_LIT:\n>'.join(parts)<EOL>rrule.save()<EOL><DEDENT><DEDENT>
"0002_recurrence_rules" added malformed recurrence with trailing semi-colons. While the JS parser on the front-end handles them, the python parser will crash
f4863:m0
def forwards(apps, schema_editor):
RecurrenceRule = apps.get_model('<STR_LIT>', '<STR_LIT>')<EOL>for description, recurrence_rule in RULES:<EOL><INDENT>RecurrenceRule.objects.get_or_create(<EOL>description=description,<EOL>defaults=dict(recurrence_rule=recurrence_rule),<EOL>)<EOL><DEDENT>
Create initial recurrence rules.
f4867:m0
def backwards(apps, schema_editor):
RecurrenceRule = apps.get_model('<STR_LIT>', '<STR_LIT>')<EOL>descriptions = [d for d, rr in RULES]<EOL>RecurrenceRule.objects.filter(description__in=descriptions).delete()<EOL>
Delete initial recurrence rules.
f4867:m1
def recurrence_rule(value):
try:<EOL><INDENT>rrule.rrulestr(value)<EOL><DEDENT>except ValueError:<EOL><INDENT>raise ValidationError(<EOL>_('<STR_LIT>'),<EOL>code='<STR_LIT>')<EOL><DEDENT>
Validate that a ``rruleset`` object can be creted from ``value``.
f4877:m0
def index(request):
warnings.warn(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>, DeprecationWarning<EOL>)<EOL>occurrences = models.Occurrence.objects.visible()<EOL>context = {<EOL>'<STR_LIT>': occurrences,<EOL>}<EOL>return TemplateResponse(request, '<STR_LIT>', context)<EOL>
Listing page for event `Occurrence`s. :param request: Django request object. :param is_preview: Should the listing page be generated as a preview? This will allow preview specific actions to be done in the template such as turning off tracking options or adding links to the admin. :return: TemplateResponse
f4879:m0
def event(request, slug):
<EOL>event = get_object_or_404(models.EventBase.objects.visible(), slug=slug)<EOL>context = RequestContext(request, {<EOL>'<STR_LIT>': event,<EOL>'<STR_LIT>': event,<EOL>})<EOL>template = getattr(event, '<STR_LIT>', '<STR_LIT>')<EOL>return TemplateResponse(request, template, context)<EOL>
:param request: Django request object. :param event_id: The `id` associated with the event. :param is_preview: Should the listing page be generated as a preview? This will allow preview specific actions to be done in the template such as turning off tracking options or adding links to the admin. :return: TemplateResponse
f4879:m1
def occurrence(request, event_id, occurrence_id):
<EOL>warnings.warn(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>, DeprecationWarning<EOL>)<EOL>try:<EOL><INDENT>occurrence = models.Occurrence.objects.filter(event_id=event_id, id=occurrence_id).visible()[<NUM_LIT:0>]<EOL><DEDENT>except IndexError:<EOL><INDENT>raise Http404<EOL><DEDENT>context = {<EOL>'<STR_LIT>': occurrence,<EOL>}<EOL>return TemplateResponse(<EOL>request, '<STR_LIT>', context)<EOL>
:param request: Django request object. :param event_id: The `id` associated with the occurrence's event. :param occurrence_id: The `id` associated with the occurrence. :param is_preview: Should the listing page be generated as a preview? This will allow preview specific actions to be done in the template such as turning off tracking options or adding links to the admin. :return: TemplateResponse
f4879:m3
def __init__(self, *args, **kwargs):
widgets = kwargs.pop('<STR_LIT>', (<EOL>forms.Select,<EOL>AdminTextareaWidget,<EOL>AdminTextareaWidget,<EOL>))<EOL>super(RecurrenceRuleWidget, self).__init__(<EOL>widgets=widgets, *args, **kwargs)<EOL>self.queryset = models.RecurrenceRule.objects.all()<EOL>
Set the default widgets and queryset.
f4880:c0:m0
def _get_choices(self):
return self.widgets[<NUM_LIT:0>].choices<EOL>
Return choices from the ``Select`` widget.
f4880:c0:m1
def _set_choices(self, value):
self.widgets[<NUM_LIT:0>].choices = value<EOL>
Set choices on the ``Select`` widget.
f4880:c0:m2
def decompress(self, value):
if value:<EOL><INDENT>try:<EOL><INDENT>pk = self.queryset.get(recurrence_rule=value).pk<EOL><DEDENT>except self.queryset.model.DoesNotExist:<EOL><INDENT>pk = None<EOL><DEDENT>return [pk, None, value]<EOL><DEDENT>return [None, None, None]<EOL>
Return the primary key value for the ``Select`` widget if the given recurrence rule exists in the queryset.
f4880:c0:m3
def format_output(self, rendered_widgets):
template = loader.get_template(<EOL>'<STR_LIT>')<EOL>preset, natural, rfc = rendered_widgets<EOL>context = Context({<EOL>'<STR_LIT>': preset,<EOL>'<STR_LIT>': natural,<EOL>'<STR_LIT>': rfc,<EOL>})<EOL>return template.render(context)<EOL>
Render the ``icekit_events/recurrence_rule_widget/format_output.html`` template with the following context: preset A choice field for preset recurrence rules. natural An input field for natural language recurrence rules. rfc A text field for RFC compliant recurrence rules. The default template positions the ``preset`` field above the ``natural`` and ``rfc`` fields.
f4880:c0:m4
def render(self, name, value, attrs=None):
rendered_widgets = super(RecurrenceRuleWidget, self).render(<EOL>name, value, attrs)<EOL>template = loader.get_template(<EOL>'<STR_LIT>')<EOL>recurrence_rules = json.dumps(dict(<EOL>self.queryset.values_list('<STR_LIT>', '<STR_LIT>')))<EOL>context = Context({<EOL>'<STR_LIT>': rendered_widgets,<EOL>'<STR_LIT:id>': attrs['<STR_LIT:id>'],<EOL>'<STR_LIT>': recurrence_rules,<EOL>})<EOL>return template.render(context)<EOL>
Render the ``icekit_events/recurrence_rule_widget/render.html`` template with the following context: rendered_widgets The rendered widgets. id The ``id`` attribute from the ``attrs`` keyword argument. recurrence_rules A JSON object mapping recurrence rules to their primary keys. The default template adds JavaScript event handlers that update the ``Textarea`` and ``Select`` widgets when they are updated.
f4880:c0:m5
def __init__(self, *args, **kwargs):
<EOL>queryset = kwargs.pop('<STR_LIT>', models.RecurrenceRule.objects.all())<EOL>max_length = kwargs.pop('<STR_LIT:max_length>', None)<EOL>validators_ = kwargs.pop('<STR_LIT>', [validators.recurrence_rule])<EOL>fields = (<EOL>forms.ModelChoiceField(queryset=queryset, required=False),<EOL>forms.CharField(required=False),<EOL>forms.CharField(max_length=max_length, validators=validators_),<EOL>)<EOL>kwargs.setdefault('<STR_LIT>', fields)<EOL>kwargs.setdefault('<STR_LIT>', False)<EOL>super(RecurrenceRuleField, self).__init__(*args, **kwargs)<EOL>self.queryset = queryset<EOL>
Set the default fields and queryset.
f4880:c1:m0
def compress(self, values):
if values:<EOL><INDENT>return values[<NUM_LIT:2>]<EOL><DEDENT>
Always return the value from the RFC field, even when a preset is selected. The recurrence rule is always defined in the RFC field.
f4880:c1:m1
def _get_queryset(self):
return self.fields[<NUM_LIT:0>].queryset<EOL>
Return the queryset from the ``ModelChoiceField``.
f4880:c1:m2
def _set_queryset(self, queryset):
self.fields[<NUM_LIT:0>].queryset = self.widget.queryset = queryset<EOL>self.widget.choices = self.fields[<NUM_LIT:0>].choices<EOL>
Set the queryset on the ``ModelChoiceField`` and choices on the widget.
f4880:c1:m3
def filter_content_types(self, content_type_qs):
valid_ct_ids = []<EOL>for ct in content_type_qs:<EOL><INDENT>model = ct.model_class()<EOL>if model and issubclass(model, EventBase):<EOL><INDENT>valid_ct_ids.append(ct.id)<EOL><DEDENT><DEDENT>return content_type_qs.filter(pk__in=valid_ct_ids)<EOL>
Filter the content types selectable to only event subclasses
f4890:c0:m0
def with_upcoming_occurrences(self):
return self.filter(<EOL>Q(is_drop_in=False, occurrences__start__gte=djtz.now) |<EOL>Q(Q(is_drop_in=True) | Q(occurrences__is_all_day=True), occurrences__end__gt=djtz.now)<EOL>)<EOL>
:return: events having upcoming occurrences, and all their children
f4902:c0:m0
def with_upcoming_or_no_occurrences(self):
ids = set(self.with_upcoming_occurrences().values_list('<STR_LIT:id>', flat=True)) | set(self.with_no_occurrences().values_list('<STR_LIT:id>', flat=True))<EOL>return self.model.objects.filter(id__in=ids)<EOL>
:return:
f4902:c0:m2
def order_by_first_occurrence(self):
def _key(e):<EOL><INDENT>try:<EOL><INDENT>return e.occurrence_list[<NUM_LIT:0>].start<EOL><DEDENT>except IndexError: <EOL><INDENT>return localize(datetime.max - timedelta(days=<NUM_LIT>))<EOL><DEDENT><DEDENT>return sorted(list(self), key=_key)<EOL>
:return: The event in order of minimum occurrence.
f4902:c0:m8
def order_by_next_occurrence(self):
qs = self.prefetch_related('<STR_LIT>')<EOL>def _sort(x):<EOL><INDENT>try:<EOL><INDENT>return x.get_next_occurrence().start<EOL><DEDENT>except AttributeError:<EOL><INDENT>try:<EOL><INDENT>return x.get_first_occurrence().start + timedelta(days=<NUM_LIT:1000>*<NUM_LIT>)<EOL><DEDENT>except AttributeError:<EOL><INDENT>return make_aware(datetime.max-timedelta(<NUM_LIT:2>))<EOL><DEDENT><DEDENT><DEDENT>sorted_qs = sorted(qs, key=_sort)<EOL>return sorted_qs<EOL>
:return: A list of events in order of minimum occurrence greater than now (or overlapping now in the case of drop-in events). This is an expensive operation - use with as small a source queryset as possible. Events with no upcoming occurrence appear last (in order of their first occurrence). Events with no occurrences at all appear right at the end (in no order). To remove these, use "with_upcoming_occurrences" or "with_upcoming_or_no_occurrences".
f4902:c0:m9
def overlapping(self, start=None, end=None):
qs = self<EOL>if start:<EOL><INDENT>dt_start=coerce_dt_awareness(start)<EOL>qs = qs.filter(<EOL>Q(is_all_day=False, end__gt=dt_start) |<EOL>Q(is_all_day=True, end__gte=zero_datetime(dt_start))<EOL>)<EOL><DEDENT>if end:<EOL><INDENT>dt_end=coerce_dt_awareness(end, t=time.max)<EOL>qs = qs.filter(<EOL>Q(is_all_day=False, start__lt=dt_end) |<EOL>Q(is_all_day=True, start__lt=zero_datetime(dt_end))<EOL>)<EOL><DEDENT>return qs<EOL>
:return: occurrences overlapping the given start and end datetimes, inclusive. Special logic is applied for all-day occurrences, for which the start and end times are zeroed to find all occurrences that occur on a DATE as opposed to within DATETIMEs.
f4902:c1:m8
def starts_within(self, start=None, end=None):
qs = self<EOL>if start:<EOL><INDENT>dt_start=coerce_dt_awareness(start)<EOL>qs = qs.filter(<EOL>Q(is_all_day=False, start__gte=dt_start) |<EOL>Q(is_all_day=True, start__gte=zero_datetime(dt_start))<EOL>)<EOL><DEDENT>if end:<EOL><INDENT>dt_end=coerce_dt_awareness(end, t=time.max)<EOL>qs = qs.filter(<EOL>Q(is_all_day=False, start__lt=dt_end) |<EOL>Q(is_all_day=True, start__lte=zero_datetime(dt_end))<EOL>)<EOL><DEDENT>return qs<EOL>
:return: normal occurrences that start within the given start and end datetimes, inclusive, and drop-in occurrences that
f4902:c1:m9
def available_within(self, start=None, end=None):
return self.filter(event__is_drop_in=False).starts_within(start, end) |self.filter(event__is_drop_in=True).overlapping(start, end)<EOL>
:return: Normal events that start within the range, and drop-in events that overlap the range.
f4902:c1:m10
def available_on_day(self, day):
if isinstance(day, datetime):<EOL><INDENT>d = day.date()<EOL><DEDENT>else:<EOL><INDENT>d = day<EOL><DEDENT>return self.starts_within(d, d)<EOL>
Return events that are available on a given day.
f4902:c1:m11
def _same_day_ids(self):
<EOL>qs = self.filter(end__lte=F('<STR_LIT:start>') + timedelta(days=<NUM_LIT:1>))<EOL>ids = [o.id for o in qs if (<EOL>(o.local_start.date() == o.local_end.date()) or<EOL>(<EOL>o.local_end.time() == time(<NUM_LIT:0>,<NUM_LIT:0>) and<EOL>o.local_end.date() == o.local_start.date() + timedelta(days=<NUM_LIT:1>) and<EOL>o.is_all_day == False<EOL>)<EOL>)]<EOL>return ids<EOL>
:return: ids of occurrences that finish on the same day that they start, or midnight the next day.
f4902:c1:m12
def same_day(self):
return self.filter(id__in=self._same_day_ids())<EOL>
:return: occurrences that finish on the same day that they start, or midnight the next day. These types of occurrences sometimes need to be treated differently.
f4902:c1:m13
def different_day(self):
<EOL>return self.exclude(id__in=self._same_day_ids())<EOL>
:return: occurrences that finish on the a different day than they start, unless it's midnight the next day. These types of occurrences sometimes need to be treated differently.
f4902:c1:m14
def upcoming(self):
return self.available_within(start=djtz.now(), end=None)<EOL>
:return: If the event is drop-in, return occurrences that overlap now until any time in the future. If the event is not drop-in, return occurrences that start in the future. Occurrences are ordered by their `start` by default.
f4902:c1:m15
def next_occurrence(self):
try:<EOL><INDENT>return self.upcoming()[<NUM_LIT:0>]<EOL><DEDENT>except IndexError:<EOL><INDENT>return None<EOL><DEDENT>
:return: The next occurrence of the event, or current occurrence if the event is a drop-in.
f4902:c1:m16
def round_datetime(when=None, precision=<NUM_LIT>, rounding=ROUND_NEAREST):
when = when or djtz.now()<EOL>weekday = WEEKDAYS.get(precision, WEEKDAYS['<STR_LIT>'])<EOL>if precision in WEEKDAYS:<EOL><INDENT>precision = int(timedelta(days=<NUM_LIT:7>).total_seconds())<EOL><DEDENT>elif isinstance(precision, timedelta):<EOL><INDENT>precision = int(precision.total_seconds())<EOL><DEDENT>when_min = when.min + timedelta(days=weekday)<EOL>if djtz.is_aware(when):<EOL><INDENT>when_min = datetime(tzinfo=when.tzinfo, *when_min.timetuple()[:<NUM_LIT:3>])<EOL><DEDENT>delta = when - when_min<EOL>remainder = int(delta.total_seconds()) % precision<EOL>when -= timedelta(seconds=remainder, microseconds=when.microsecond)<EOL>if rounding == ROUND_UP or (<EOL>rounding == ROUND_NEAREST and remainder >= precision / <NUM_LIT:2>):<EOL><INDENT>when += timedelta(seconds=precision)<EOL><DEDENT>return when<EOL>
Round a datetime object to a time that matches the given precision. when (datetime), default now The datetime object to be rounded. precision (int, timedelta, str), default 60 The number of seconds, weekday (MON, TUE, WED, etc.) or timedelta object to which the datetime object should be rounded. rounding (str), default ROUND_NEAREST The rounding method to use (ROUND_DOWN, ROUND_NEAREST, ROUND_UP).
f4903:m0
def zero_datetime(dt, tz=None):
if tz is None:<EOL><INDENT>tz = get_current_timezone()<EOL><DEDENT>return coerce_naive(dt).replace(hour=<NUM_LIT:0>, minute=<NUM_LIT:0>, second=<NUM_LIT:0>, microsecond=<NUM_LIT:0>)<EOL>
Return the given datetime with hour/minutes/seconds/ms zeroed and the timezone coerced to the given ``tz`` (or UTC if none is given).
f4903:m1
def coerce_dt_awareness(date_or_datetime, tz=None, t=None):
if isinstance(date_or_datetime, datetime):<EOL><INDENT>dt = date_or_datetime<EOL><DEDENT>else:<EOL><INDENT>dt = datetime.combine(date_or_datetime, t or time.min)<EOL><DEDENT>is_project_tz_aware = settings.USE_TZ<EOL>if is_project_tz_aware:<EOL><INDENT>return coerce_aware(dt, tz)<EOL><DEDENT>elif not is_project_tz_aware:<EOL><INDENT>return coerce_naive(dt, tz)<EOL><DEDENT>return dt<EOL>
Coerce the given `datetime` or `date` object into a timezone-aware or timezone-naive `datetime` result, depending on which is appropriate for the project's settings.
f4903:m2
def format_naive_ical_dt(date_or_datetime):
dt = coerce_dt_awareness(date_or_datetime)<EOL>if is_naive(dt):<EOL><INDENT>return dt.strftime('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>return dt.astimezone(get_current_timezone()).strftime('<STR_LIT>')<EOL><DEDENT>
Return datetime formatted for use in iCal as a *naive* datetime value to work more like people expect, e.g. creating a series of events starting at 9am should not create some occurrences that start at 8am or 10am after a daylight savings change.
f4903:m5