def get_template_names(self): model = self.parent.content_object.__class__ return ( "comments/{0}_{1}_preview.html".format(get_meta(model).app_label, get_meta(model).model_name), "comments/{0}_preview.html".format(get_meta(model).app_label), "comments/preview.html", )
def get_template_names(self): model = self.parent.content_object.__class__ return ( 'comments/{0}_{1}_preview.html'.format( get_meta(model).app_label, get_meta(model).model_name), 'comments/{0}_preview.html'.format(get_meta(model).app_label), 'comments/preview.html', )
def upload_to(instance, filename): content_class = instance.content_type.model_class() return 'attachment/{0}_{1}/{2:02x}/{3}/{4}'.format( get_meta(content_class).app_label, get_meta(content_class).object_name.lower(), instance.object_id % 256, instance.object_id, filename )
def render_comments_toplevel(context, target): context = dict(context) model_class = target.__class__ templates = ( "comments/{0}_{1}_comments_toplevel.html".format(*str(get_meta(model_class)).split('.')), "comments/{0}_comments_toplevel.html".format(get_meta(model_class).app_label), "comments/comments_toplevel.html", ) context.update({"target": target}) return mark_safe(render_to_string(templates, context))
def set_ip_for_object(self, instance, **kwargs): opts = get_meta(instance) model = (opts.app_label, opts.model_name) if model in SET_IP_MODELS: request = get_current_request() if request: instance.ip_address = get_client_ip(request)
def reply_comment(request, parent): parent_comment = get_object_or_404(Comment.all_comments, pk = parent) content_object = parent_comment.content_object if parent_comment.parent_id: new_subject = parent_comment.subject if not new_subject.startswith(force_unicode('RE: ')): new_subject = force_unicode('RE: ') + new_subject else: new_subject = force_unicode('RE: ') + force_unicode(content_object) model_meta = get_meta(content_object) template_list = [ "comments/{0}_{1}_preview.html".format(*tuple(str(model_meta).split('.'))), "comments/{0}_preview.html".format(model_meta.app_label), "comments/preview.html", ] next = request.GET.get('next', content_object.get_absolute_url()) context = { 'next': next, 'parent': parent_comment if parent_comment.parent_id else False, 'content_object': content_object, 'module_name': get_module_name(content_object), 'module_url': get_module_url(content_object), } if parent_comment.is_locked: return TemplateResponse(request, "comments/error.html", context) form = get_form()(content_object, logged = request.user.is_authenticated(), parent_comment = parent_comment, initial = {'subject': new_subject}) context["form"] = form context["attachments"] = form.get_attachments() return TemplateResponse(request, template_list, context)
def unique_slugify(self, instance, **kwargs): slug = getattr(instance, self.name) if not slug: if self.title_field: slug = slugify(getattr(instance, self.title_field)) else: return if not slug: slug = '-' slug_field = get_meta(instance).get_field(self.name) slug_length = slug_field.max_length slug = slug[:slug_length - self.reserve_chars] queryset = get_default_manager(instance).all() if instance.pk: queryset = queryset.exclude(pk=instance.pk) slug_field_query = self.name + '__startswith' filter_fields = dict([(f, getattr(instance, f)) for f in self.filter_fields]) filter_fields[slug_field_query] = slug all_slugs = set(queryset.filter(**filter_fields).values_list(self.name, flat=True)) max_val = 10 ** (self.reserve_chars - 1) - 1 setattr(instance, self.name, self.create_unique_slug(slug, all_slugs, max_val))
def get_context_data(self, **kwargs): ctx = super().get_context_data(**kwargs) content_object = self.object.statistics.content_object ctx.update({ 'object_type_verbose_name': get_meta(content_object).verbose_name if content_object else '', 'object': self.object, }) return ctx
def get_context_data(self, **kwargs): ctx = super().get_context_data(object=self.flagged_object, **kwargs) ctx.update({ 'content_object': self.flagged_object, 'module_name': get_module_name(self.flagged_object), 'module_url': get_module_url(self.flagged_object), 'object_type_verbose_name': get_meta(self.flagged_object).verbose_name.lower(), 'object': self.object, }) return ctx
def generate_security_data(self): timestamp = int(time()) security_dict = { 'content_type': str(get_meta(self.target_object)), 'object_id': str(self.target_object.pk), 'parent_pk': str(self.parent_comment.pk), 'timestamp': str(timestamp), 'security_hash': self.initial_security_hash(timestamp), } return security_dict
def time_series(qs, date_field, aggregate, interval, date_from=None, date_to=None): current_timezone = timezone.get_current_timezone() is_date = interval in DATE_SERIES is_week = interval == 'week' if is_week: interval = 'day' if isinstance(get_meta(qs.model).get_field(date_field), models.DateTimeField): db_interval = DateTime(date_field, interval, current_timezone) else: db_interval = Date(date_field, interval) if not isinstance(aggregate, dict): aggregate = {'aggregate': aggregate} SeriesRecord = namedtuple('SeriesRecord', ['time_value'] + aggregate.keys()) if is_date: if date_from and not isinstance(date_from, datetime): date_from = current_timezone.localize(datetime.combine(date_from, time.min)) if date_to and not isinstance(date_to, datetime): date_to = current_timezone.localize(datetime.combine(date_to, time.max)) if date_from is not None: qs = qs.filter(**{date_field + '__gte': date_from}) if date_to is not None: qs = qs.filter(**{date_field + '__lte': date_to}) qs = (qs .annotate(time_value=db_interval) .values_list('time_value') .order_by('time_value') .annotate(**aggregate) ) def convert_date(val): if is_date and isinstance(val, datetime): return val.date() return val records = [SeriesRecord(convert_date(val[0]), *val[1:]) for val in qs] if len(records): date_from = date_from or records[0].time_value date_to = date_to or records[-1].time_value empty_record = partial(SeriesRecord, **{k: None for k in aggregate.keys()}) records = fill_time_series_gap(records, empty_record, interval, date_from, date_to) if is_week: records = sum_weeks(set_gaps_zero(records)) return records
def delete_model_cache(sender, **kwargs): meta = get_meta(sender) tag_name = '%s.%s' % (meta.app_label, meta.model_name) cache_instance.delete_tag(tag_name) if tag_name == 'comments.rootheader': cache_instance.delete_tag('forum.topic')
def labelize_content_type(content_type): app_label, model = content_type.split('.') return get_meta(ContentType.objects.get_by_natural_key(app_label=app_label, model=model).model_class()).verbose_name
def get_verbose_name_plural(self): return capfirst(self.verbose_name_plural or get_meta(self.get_queryset().model).verbose_name_plural)
def clear_last_objects_cache(sender, **kwargs): opts = get_meta(sender) if '.'.join((opts.app_label, opts.model_name)) not in MODELS: return default_cache.delete('last_objects')
def delete_table(cls): cursor = connection.cursor() try: cursor.execute('DROP TABLE IF EXISTS %s' % get_meta(cls).db_table) finally: cursor.close()
def post_comment(request): data = request.POST.copy() if request.user.is_authenticated(): data['email'] = request.user.email if request.user.get_full_name(): data['name'] = request.user.get_full_name() else: data['name'] = request.user.username else: data['email'] = '*****@*****.**' if not data['content_type'] or not data['object_id'] or not data['parent_pk']: return http.HttpResponseBadRequest() model = models.get_model(*data['content_type'].split(".", 1)) target = get_default_manager(model).get(pk = data['object_id']) parent = Comment.all_comments.get(pk = data['parent_pk']) content_object = parent.content_object form = get_form()(target, logged = request.user.is_authenticated(), parent_comment = parent, data = data, files = request.FILES) if form.security_errors(): return http.HttpResponseBadRequest() if form.errors or not 'create' in data or parent.is_locked: template_list = [ "comments/{0}_{1}_preview.html".format(get_meta(model).app_label, get_meta(model).module_name), "comments/{0}_preview.html".format(get_meta(model).app_label), "comments/preview.html", ] valid = not form.errors comment = form.get_comment() if request.user.is_authenticated(): comment.user = request.user context = { 'next': data['next'], 'comment': comment, 'valid': valid, 'parent': parent if parent.parent_id else False, 'content_object': content_object, 'module_name': get_module_name(content_object), 'module_url': get_module_url(content_object), 'form': form, 'attachments': form.get_attachments(), } if parent.is_locked: del context['form'] del context['attachments'] return TemplateResponse(request, "comments/error.html", context) return TemplateResponse(request, template_list, context) comment = form.get_comment_object() comment.ip_address = request.META.get("REMOTE_ADDR", None) if request.user.is_authenticated(): comment.user = request.user comment.save() form.move_attachments(comment) data['next'] = data['next'] + '#link_' + str(comment.pk) return HttpResponseRedirect(data['next'])
def setUp(self): self.testContentType = ContentType.objects.all()[0] self.ct = get_meta(self.testContentType.model_class()).db_table
def get_module_name(content_object): if hasattr(content_object, 'breadcrumb_label'): return capfirst(content_object.breadcrumb_label) else: return capfirst(get_meta(content_object).verbose_name_plural)
def delete_model_cache(sender, **kwargs): meta = get_meta(sender) tag_name = "%s.%s" % (meta.app_label, meta.model_name) cache_instance.delete_tag(tag_name) if tag_name == "threaded_comments.rootheader": cache_instance.delete_tag("forum.topic")
def labelize_content_type(content_type): app_label, model = content_type.split('.') return get_meta( ContentType.objects.get_by_natural_key( app_label=app_label, model=model).model_class()).verbose_name
def time_series(qs, date_field, aggregate, interval, date_from=None, date_to=None): # pylint: disable=too-many-arguments current_timezone = timezone.get_current_timezone() is_date = interval in DATE_SERIES is_week = interval == 'week' if is_week: interval = 'day' if isinstance( get_meta(qs.model).get_field(date_field), models.DateTimeField): db_interval = Trunc(date_field, interval, output_field=DateTimeField(), tzinfo=current_timezone) else: db_interval = Trunc(date_field, interval, output_field=DateField()) if not isinstance(aggregate, dict): aggregate = {'aggregate': aggregate} SeriesRecord = namedtuple('SeriesRecord', ['time_value'] + list(aggregate.keys())) if is_date: if date_from and not isinstance(date_from, datetime): date_from = current_timezone.localize( datetime.combine(date_from, time.min)) if date_to and not isinstance(date_to, datetime): date_to = current_timezone.localize( datetime.combine(date_to, time.max)) if date_from is not None: qs = qs.filter(**{date_field + '__gte': date_from}) if date_to is not None: qs = qs.filter(**{date_field + '__lte': date_to}) qs = (qs.annotate(time_value=db_interval).values_list( 'time_value').order_by('time_value').annotate(**aggregate)) def convert_date(val): if is_date and isinstance(val, datetime): return val.date() return val records = [SeriesRecord(convert_date(val[0]), *val[1:]) for val in qs] if len(records): date_from = date_from or records[0].time_value date_to = date_to or records[-1].time_value empty_record = partial(SeriesRecord, **{k: None for k in aggregate.keys()}) records = fill_time_series_gap(records, empty_record, interval, date_from, date_to) if is_week: records = sum_weeks(set_gaps_zero(records)) return records
class Meta: app_label = get_meta(AttachmentImage).app_label db_table = get_meta(AttachmentImage).db_table managed = False
def get_verbose_name_plural(self): return capfirst( self.verbose_name_plural or get_meta(self.get_queryset().model).verbose_name_plural)