def get_verbose_name(self): """ Returns the verbose name of the document. Checks the original meta dict first. If it is not found then generates a verbose name from from the object name. """ try: return capfirst(get_verbose_name(self._meta['verbose_name'])) except KeyError: return capfirst(get_verbose_name(self.object_name))
def verbose_name(self): """ Returns the verbose name of the document. Checks the original meta dict first. If it is not found then generates a verbose name from from the object name. """ if self._verbose_name is None: try: self._verbose_name = capfirst(get_verbose_name(self._meta["verbose_name"])) except KeyError: self._verbose_name = capfirst(get_verbose_name(self.object_name)) return self._verbose_name
def __init__(self, name, func_get_value_from_object=None, abstract=None, doc=None, analyzer=None): self.name = name self.verbose_name = get_verbose_name(self.name) self.store = self.store self.tokenize = self.tokenize if self.abstract is not None: self.abstract = abstract else: self.abstract = self.abstract self.doc = doc self.initialize() if func_get_value_from_object: self.func_get_value_from_object = func_get_value_from_object # set analyzer if analyzer and constant.ANALYZERS.has_key(analyzer): self.analyzer = constant.ANALYZERS.get(analyzer)()
def contribute_to_class(self, cls, name): from django.db.backends.util import truncate_name cls._meta = self self.installed = re.sub('\.models$', '', cls.__module__) in settings.INSTALLED_APPS # First, construct the default values for these options. self.object_name = cls.__name__ self.module_name = self.object_name.lower() self.verbose_name = get_verbose_name(self.object_name) # Next, apply any overridden values from 'class Meta'. if self.meta: meta_attrs = self.meta.__dict__.copy() for name in self.meta.__dict__: # Ignore any private attributes that Django doesn't care about. # NOTE: We can't modify a dictionary's contents while looping # over it, so we loop over the *original* dictionary instead. if name.startswith('_'): del meta_attrs[name] for attr_name in DEFAULT_NAMES: if attr_name in meta_attrs: setattr(self, attr_name, meta_attrs.pop(attr_name)) elif hasattr(self.meta, attr_name): setattr(self, attr_name, getattr(self.meta, attr_name)) # verbose_name_plural is a special case because it uses a 's' # by default. setattr(self, 'verbose_name_plural', meta_attrs.pop('verbose_name_plural', string_concat(self.verbose_name, 's'))) # Any leftover attributes must be invalid. if meta_attrs != {}: raise TypeError("'class Meta' got invalid attribute(s): %s" % ','.join(meta_attrs.keys())) else: self.verbose_name_plural = string_concat(self.verbose_name, 's') del self.meta
def healthcheck(func_or_name): """ Health check decorator. Usage: @healthcheck("My Check") def my_check(): if something_is_not_okay(): raise ServiceReturnedUnexpectedResult() @healthcheck def other_check(): if something_is_not_available(): raise ServiceUnavailable() """ def inner(func): cls = type(func.__name__, (BaseHealthCheck,), {'_wrapped': staticmethod(func)}) cls.identifier = name plugin_dir.register(cls) return func if callable(func_or_name): name = get_verbose_name(func_or_name.__name__).replace('_', ' ') return inner(func_or_name) else: name = func_or_name return inner
def reverse_translate_query(query): new_query_string = u'' for i in query.lists(): # modelname=i[0] modelstring = get_verbose_name(i[0]) value = i[1] if modelstring in fixed_fields: new_query_string += "&" + modelstring + "=" + value[0] elif modelstring[0:7] == 'incluir': new_query_string += "&" + modelstring else: modelname = ' '.join(modelstring.split()[1:]) appname = modelstring.split()[0] ctype_list = ContentType.objects.filter(app_label=appname, name=modelname) if len(ctype_list) > 0: ctype = ctype_list[0] model_class = ctype.model_class() for b in value: d = model_class.objects.filter(pk=b) if len(d) > 0: new_query_string += "&" + modelstring + "=" + d[ 0].nombre new_query_string = new_query_string.lstrip("&") return new_query_string
def view(request): name = get_verbose_name(type(self).__name__).replace(' ','_') context = { 'form': self.form, } template = getattr(self, 'search_template', 'search/search_%s.html' % name) return TemplateResponse(request, template, context)
def contribute_to_class(self, cls, name): cls._meta = self self.installed = re.sub('\.models$', '', cls.__module__) in settings.INSTALLED_APPS # First, construct the default values for these options. self.object_name = cls.__name__ self.module_name = self.object_name.lower() self.verbose_name = get_verbose_name(self.object_name) # Next, apply any overridden values from 'class Meta'. if self.meta: meta_attrs = self.meta.__dict__.copy() for name in self.meta.__dict__: # Ignore any private attributes that Django doesn't care about. # NOTE: We can't modify a dictionary's contents while looping # over it, so we loop over the *original* dictionary instead. if name.startswith('_'): del meta_attrs[name] for attr_name in DEFAULT_NAMES: if attr_name in meta_attrs: setattr(self, attr_name, meta_attrs.pop(attr_name)) elif hasattr(self.meta, attr_name): setattr(self, attr_name, getattr(self.meta, attr_name)) # verbose_name_plural is a special case because it uses a 's' # by default. setattr(self, 'verbose_name_plural', meta_attrs.pop('verbose_name_plural', string_concat(self.verbose_name, 's'))) # Any leftover attributes must be invalid. if meta_attrs != {}: raise TypeError("'class Meta' got invalid attribute(s): %s" % ','.join(meta_attrs.keys())) else: self.verbose_name_plural = string_concat(self.verbose_name, 's') del self.meta
def view(request): results =[] query = None formclass = self.category_search_form() if request.GET: # this uses GET, not POST. so the way to realize if data # is being posted and we need a form bound, instead of # needing an empty unbound form, is checking request.GET form = formclass(request.GET) self._set_choices(form) if form.is_valid(): category_list = self.category_instances if 'category' in form.cleaned_data: category_index = form.cleaned_data['category'] if category_index != '': category_list = [self.category_instances[category_index]] for c in category_list: results.append((c, c.get_results(form.cleaned_data, request))) query = form.cleaned_data else: form = formclass() self._set_choices(form) context = { 'form': form, 'results': results, 'query_data': query } name = get_verbose_name(type(self).__name__).replace(' ','_') template = getattr(self, 'search_template', 'search/results_%s.html' % name) return TemplateResponse(request, template, context)
def healthcheck(func_or_name): """ Usage: @healthcheck("My Check") def my_check(): if something_is_not_okay(): raise ServiceReturnedUnexpectedResult() @healthcheck def other_check(): if something_is_not_available(): raise ServiceUnavailable() """ def inner(func): cls = type(func.__name__, (BaseHealthCheck, ), {'_wrapped': staticmethod(func)}) cls.identifier = name plugin_dir.register(cls) return func if callable(func_or_name): name = get_verbose_name(func_or_name.__name__).replace('_', ' ') return inner(func_or_name) else: name = func_or_name return inner
def __new__(cls, name, bases, attrs): super_new = super(CMSPluginBaseMetaclass, cls).__new__ parents = [base for base in bases if isinstance(base, CMSPluginBaseMetaclass)] if not parents: # If this is CMSPluginBase itself, and not a subclass, don't do anything return super_new(cls, name, bases, attrs) new_plugin = super_new(cls, name, bases, attrs) # validate model is actually a CMSPlugin subclass. if not issubclass(new_plugin.model, CMSPlugin): raise SubClassNeededError( "The 'model' attribute on CMSPluginBase subclasses must be " "either CMSPlugin or a subclass of CMSPlugin. %r on %r is not." % (new_plugin.model, new_plugin) ) # validate the template: if not hasattr(new_plugin, 'render_template'): raise ImproperlyConfigured( "CMSPluginBase subclasses must have a render_template attribute" ) # Set the default form if not new_plugin.form: form_meta_attrs = { 'model': new_plugin.model, 'exclude': ('position', 'placeholder', 'language', 'plugin_type') } form_attrs = { 'Meta': type('Meta', (object,), form_meta_attrs) } new_plugin.form = type('%sForm' % name, (ModelForm,), form_attrs) # Set the default fieldsets if not new_plugin.fieldsets: basic_fields = [] advanced_fields = [] for f in new_plugin.model._meta.fields: if not f.auto_created and f.editable: if hasattr(f,'advanced'): advanced_fields.append(f.name) else: basic_fields.append(f.name) if advanced_fields: new_plugin.fieldsets = [ ( None, { 'fields': basic_fields } ), ( _('Advanced options'), { 'fields' : advanced_fields, 'classes' : ('collapse',) } ) ] # Set default name if not new_plugin.name: new_plugin.name = get_verbose_name(new_plugin.__name__) return new_plugin
def __new__(cls, name, bases, attrs): super_new = super(CMSPluginBaseMetaclass, cls).__new__ parents = [base for base in bases if isinstance(base, CMSPluginBaseMetaclass)] if not parents: # If this is CMSPluginBase itself, and not a subclass, don't do anything return super_new(cls, name, bases, attrs) new_plugin = super_new(cls, name, bases, attrs) # validate model is actually a CMSPlugin subclass. if not issubclass(new_plugin.model, CMSPlugin): raise SubClassNeededError( "The 'model' attribute on CMSPluginBase subclasses must be " "either 'None' or a subclass of CMSPlugin. %r on %r is not." % (new_plugin.model, new_plugin) ) # validate the template: if not hasattr(new_plugin, 'render_template'): raise ImproperlyConfigured( "CMSPluginBase subclasses must have a render_template attribute" ) # Set the default form if not new_plugin.form: form_meta_attrs = { 'model': new_plugin.model, 'exclude': ('position', 'placeholder', 'language', 'plugin_type') } form_attrs = { 'Meta': type('Meta', (object,), form_meta_attrs) } new_plugin.form = type('%sForm' % name, (ModelForm,), form_attrs) # Set the default fieldsets if not new_plugin.fieldsets: basic_fields = [] advanced_fields = [] for f in new_plugin.model._meta.fields: if not f.auto_created and f.editable: if hasattr(f,'advanced'): advanced_fields.append(f.name) else: basic_fields.append(f.name) if advanced_fields: new_plugin.fieldsets = [ ( None, { 'fields': basic_fields } ), ( _('Advanced options'), { 'fields' : advanced_fields, 'classes' : ('collapse',) } ) ] # Set default name if not new_plugin.name: new_plugin.name = get_verbose_name(new_plugin.__name__) return new_plugin
def view(request): if request.GET: # We're being asked for results, actually return self.results_view(request) form = self.search_form()() context = { 'form': form, } name = get_verbose_name(type(self).__name__).replace(' ','_') template = getattr(self, 'search_template', 'search/search_%s.html' % name) return TemplateResponse(request, template, context)
def contribute_to_class(self, cls, name): from django.db import connection from django.db.backends.util import truncate_name cls._meta = self self.installed = re.sub('\.models$', '', cls.__module__) in settings.INSTALLED_APPS # First, construct the default values for these options. self.object_name = cls.__name__ self.module_name = self.object_name.lower() self.verbose_name = get_verbose_name(self.object_name) # Next, apply any overridden values from 'class Meta'. if self.meta: meta_attrs = self.meta.__dict__.copy() for name in self.meta.__dict__: # Ignore any private attributes that Django doesn't care about. # NOTE: We can't modify a dictionary's contents while looping # over it, so we loop over the *original* dictionary instead. if name.startswith('_'): del meta_attrs[name] for attr_name in DEFAULT_NAMES: if attr_name in meta_attrs: setattr(self, attr_name, meta_attrs.pop(attr_name)) elif hasattr(self.meta, attr_name): setattr(self, attr_name, getattr(self.meta, attr_name)) # unique_together can be either a tuple of tuples, or a single # tuple of two strings. Normalize it to a tuple of tuples, so that # calling code can uniformly expect that. ut = meta_attrs.pop('unique_together', self.unique_together) if ut and not isinstance(ut[0], (tuple, list)): ut = (ut, ) self.unique_together = ut # verbose_name_plural is a special case because it uses a 's' # by default. if self.verbose_name_plural is None: self.verbose_name_plural = string_concat( self.verbose_name, 's') # Any leftover attributes must be invalid. if meta_attrs != {}: raise TypeError("'class Meta' got invalid attribute(s): %s" % ','.join(meta_attrs.keys())) else: self.verbose_name_plural = string_concat(self.verbose_name, 's') del self.meta # If the db_table wasn't provided, use the app_label + module_name. if not self.db_table: self.db_table = "%s_%s" % (self.app_label, self.module_name) self.db_table = truncate_name(self.db_table, connection.ops.max_name_length())
def __init__(self, field_name=None, label=None, public=None): if field_name is not None: self.field_name = field_name if label is not None: self.label = label if self.label is None: self.label = get_verbose_name(self.field_name) if public is not None: self.public = public
def contribute_to_class(self, cls, name): from django.db import connection from django.db.backends.util import truncate_name cls._meta = self self.installed = re.sub('\.models$', '', cls.__module__) in settings.INSTALLED_APPS # First, construct the default values for these options. self.object_name = cls.__name__ self.module_name = self.object_name.lower() self.verbose_name = get_verbose_name(self.object_name) # Next, apply any overridden values from 'class Meta'. if self.meta: meta_attrs = self.meta.__dict__.copy() for name in self.meta.__dict__: # Ignore any private attributes that Django doesn't care about. # NOTE: We can't modify a dictionary's contents while looping # over it, so we loop over the *original* dictionary instead. if name.startswith('_'): del meta_attrs[name] for attr_name in DEFAULT_NAMES: if attr_name in meta_attrs: setattr(self, attr_name, meta_attrs.pop(attr_name)) elif hasattr(self.meta, attr_name): setattr(self, attr_name, getattr(self.meta, attr_name)) # unique_together can be either a tuple of tuples, or a single # tuple of two strings. Normalize it to a tuple of tuples, so that # calling code can uniformly expect that. ut = meta_attrs.pop('unique_together', self.unique_together) if ut and not isinstance(ut[0], (tuple, list)): ut = (ut,) self.unique_together = ut # verbose_name_plural is a special case because it uses a 's' # by default. if self.verbose_name_plural is None: self.verbose_name_plural = string_concat(self.verbose_name, 's') # Any leftover attributes must be invalid. if meta_attrs != {}: raise TypeError("'class Meta' got invalid attribute(s): %s" % ','.join(meta_attrs.keys())) else: self.verbose_name_plural = string_concat(self.verbose_name, 's') del self.meta # If the db_table wasn't provided, use the app_label + module_name. if not self.db_table: self.db_table = "%s_%s" % (self.app_label, self.module_name) self.db_table = truncate_name(self.db_table, connection.ops.max_name_length())
def view(request): results = None query = None form = self.form(request.GET) name = get_verbose_name(type(self).__name__).replace(' ','_') if form.is_valid(): results = self.get_results(form.cleaned_data, request) query = form.cleaned_data context = { 'form': form, 'results': results, 'query_data': query } template = getattr(self, 'results_template', 'search/results_%s.html' % name) return TemplateResponse(request, template, context)
def __new__(cls, name, bases, attrs): super_new = super(CMSPluginBaseMetaclass, cls).__new__ parents = [base for base in bases if isinstance(base, CMSPluginBaseMetaclass)] if not parents: # If this is CMSPluginBase itself, and not a subclass, don't do anything return super_new(cls, name, bases, attrs) new_plugin = super_new(cls, name, bases, attrs) # validate model is actually a CMSPlugin subclass. if not issubclass(new_plugin.model, CMSPlugin): raise SubClassNeededError( "The 'model' attribute on CMSPluginBase subclasses must be " "either CMSPlugin or a subclass of CMSPlugin. %r on %r is not." % (new_plugin.model, new_plugin) ) # validate the template: if not hasattr(new_plugin, "render_template"): raise ImproperlyConfigured("CMSPluginBase subclasses must have a render_template attribute") # Set the default form if not new_plugin.form: form_meta_attrs = { "model": new_plugin.model, "exclude": ("position", "placeholder", "language", "plugin_type"), } form_attrs = {"Meta": type("Meta", (object,), form_meta_attrs)} new_plugin.form = type("%sForm" % name, (ModelForm,), form_attrs) # Set the default fieldsets if not new_plugin.fieldsets: basic_fields = [] advanced_fields = [] for f in new_plugin.model._meta.fields: if not f.auto_created and f.editable: if hasattr(f, "advanced"): advanced_fields.append(f.name) else: basic_fields.append(f.name) if advanced_fields: new_plugin.fieldsets = [ (None, {"fields": basic_fields}), (_("Advanced options"), {"fields": advanced_fields, "classes": ("collapse",)}), ] # Set default name if not new_plugin.name: new_plugin.name = get_verbose_name(new_plugin.__name__) return new_plugin
def __init__(self, model): self.model = model self.model_name = self.model._class_name ## Set defaults if not self.list_items: self.list_items.append('__unicode__') if not self.verbose_name: self.verbose_name = get_verbose_name(self.model_name) if not self.verbose_name_plural: self.verbose_name_plural = '%ss' % self.verbose_name ## Validations for attr in self.list_items: if not hasattr(self.model, attr): raise ValueError('%s is not an attribute of %s' % (attr, self.model._class_name)) if not issubclass(MongoAdminForm, self.form): raise TypeError('Form must be subclass of MongoAdminForm')
def contribute_to_class(self, cls, name): cls._meta = self self.object_name = cls.__name__ self.verbose_name = get_verbose_name(self.object_name) if self.meta: if hasattr(self.meta, 'cf'): self.object_name = self.meta.cf meta_attrs = self.meta.__dict__.copy() for name in self.meta.__dict__: if name.startswith('_'): del meta_attrs[name] for attr_name in DEFAULT_NAMES + TRANSIT_NAMES: if attr_name in meta_attrs: setattr(self, attr_name, meta_attrs.pop(attr_name)) elif hasattr(self.meta, attr_name): setattr(self, attr_name, getattr(self.meta, attr_name)) if getattr(settings, 'RUNNING_TESTS', False): self.keyspace = 'test_%s' % self.keyspace cls.add_to_class('objects', Manager()) del self.meta
def contribute_to_class(self, cls, name): cls._meta = self self.object_name = cls.__name__ self.verbose_name = get_verbose_name(self.object_name) if self.meta: meta_attrs = self.meta.__dict__.copy() for name in self.meta.__dict__: if name.startswith('_'): del meta_attrs[name] for attr_name in DEFAULT_NAMES: if attr_name in meta_attrs: setattr(self, attr_name, meta_attrs.pop(attr_name)) elif hasattr(self.meta, attr_name): setattr(self, attr_name, getattr(self.meta, attr_name)) if not self.keyspace: raise ConfigurationError(u"No keyspace defined! Define keyspace in your model's Meta class or CASSANDRA_KEYSPACE in settings.py") if getattr(settings, 'RUNNING_TESTS', False): self.keyspace = 'test_%s' % self.keyspace cls.add_to_class('objects', Manager()) del self.meta
def reverse_translate_query(query): new_query_string=u'' for i in query.lists(): # modelname=i[0] modelstring=get_verbose_name(i[0]) value=i[1] if modelstring in fixed_fields: new_query_string+="&"+modelstring+"="+value[0] elif modelstring[0:7]=='incluir': new_query_string+="&"+modelstring else: modelname=' '.join(modelstring.split()[1:]) appname=modelstring.split()[0] ctype_list = ContentType.objects.filter(app_label=appname,name=modelname) if len(ctype_list) > 0: ctype=ctype_list[0] model_class=ctype.model_class() for b in value: d=model_class.objects.filter(pk=b) if len(d) > 0: new_query_string+="&"+modelstring+"="+d[0].nombre new_query_string=new_query_string.lstrip("&") return new_query_string
def _update_from_name(self, name): self.name = name self.verbose_name = self.verbose_name or get_verbose_name(name) self.verbose_name_plural = self.verbose_name_plural or self.verbose_name + 's'
def get_field_label(self, field): if hasattr(field, "verbose_name"): return field.verbose_name return capfirst(get_verbose_name(field.name))
def create_verbose_name(name): name = get_verbose_name(name) name.replace("_", " ") return name
def get_field_label(self, field): if field.verbose_name: return field.verbose_name return capfirst(get_verbose_name(field.name))
def verbose_name(self): """ This is used in templates to get a label for titles under this category """ return get_verbose_name(type(self).__name__)
def get_field_label(self, field): if hasattr(field, 'verbose_name'): return field.verbose_name return capfirst(get_verbose_name(field.name))
def create_verbose_name(name): name = get_verbose_name(name) name = name.replace('_', ' ') return name
def create_verbose_name(name): name = get_verbose_name(name) name.replace('_', ' ') return name
def get_verbose_name_plural(self): try: return capfirst(get_verbose_name(self._meta['verbose_name_plural'])) except KeyError: return capfirst(get_verbose_name('%s' % self.verbose_name))