コード例 #1
0
    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))
コード例 #2
0
    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
コード例 #3
0
 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)
コード例 #4
0
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
コード例 #5
0
ファイル: schema.py プロジェクト: aviflax/couchdbkit
    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
コード例 #6
0
 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)
コード例 #7
0
ファイル: plugin_base.py プロジェクト: Air51/django-cms
 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
コード例 #8
0
 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)
コード例 #9
0
ファイル: logic.py プロジェクト: romali/django-multiseek
    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
コード例 #10
0
    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())
コード例 #11
0
 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)
コード例 #12
0
ファイル: plugin_base.py プロジェクト: Nucleoos/sowing-church
 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
コード例 #13
0
ファイル: views.py プロジェクト: georgedorn/django-mongoadmin
    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')
コード例 #14
0
ファイル: options.py プロジェクト: podshumok/alexandra
    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
コード例 #15
0
ファイル: translator.py プロジェクト: ALBAstryde/albastryde
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
コード例 #16
0
ファイル: options.py プロジェクト: aryanet/alexandra
    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
コード例 #17
0
ファイル: options.py プロジェクト: bobobo1618/django-seo
 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'
コード例 #18
0
 def get_field_label(self, field):
     if hasattr(field, "verbose_name"):
         return field.verbose_name
     return capfirst(get_verbose_name(field.name))
コード例 #19
0
 def get_field_label(self, field):
     if field.verbose_name:
         return field.verbose_name
     return capfirst(get_verbose_name(field.name))
コード例 #20
0
def create_verbose_name(name):
    name = get_verbose_name(name)
    name = name.replace('_', ' ')
    return name
コード例 #21
0
 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))
コード例 #22
0
def create_verbose_name(name):
    name = get_verbose_name(name)
    name.replace("_", " ")
    return name
コード例 #23
0
 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__)