def __init__(self, required=True, widget=None, label=None, initial=None,
                 help_text=None, error_messages=None, show_hidden_initial=False,
                 validators=[], localize=False):
        # required -- Boolean that specifies whether the field is required.
        #             True by default.
        # widget -- A Widget class, or instance of a Widget class, that should
        #           be used for this Field when displaying it. Each Field has a
        #           default Widget that it'll use if you don't specify this. In
        #           most cases, the default widget is TextInput.
        # label -- A verbose name for this field, for use in displaying this
        #          field in a form. By default, Django will use a "pretty"
        #          version of the form field name, if the Field is part of a
        #          Form.
        # initial -- A value to use in this Field's initial display. This value
        #            is *not* used as a fallback if data isn't given.
        # help_text -- An optional string to use as "help text" for this Field.
        # error_messages -- An optional dictionary to override the default
        #                   messages that the field will raise.
        # show_hidden_initial -- Boolean that specifies if it is needed to render a
        #                        hidden widget with initial value after widget.
        # validators -- List of addtional validators to use
        # localize -- Boolean that specifies if the field should be localized.
        if label is not None:
            label = smart_unicode(label)
        self.required, self.label, self.initial = required, label, initial
        self.show_hidden_initial = show_hidden_initial
        if help_text is None:
            self.help_text = u''
        else:
            self.help_text = smart_unicode(help_text)
        widget = widget or self.widget
        if isinstance(widget, type):
            widget = widget()

        # Trigger the localization machinery if needed.
        self.localize = localize
        if self.localize:
            widget.is_localized = True

        # Let the widget know whether it should display as required.
        widget.is_required = self.required

        # Hook into self.widget_attrs() for any Field-specific HTML attributes.
        extra_attrs = self.widget_attrs(widget)
        if extra_attrs:
            widget.attrs.update(extra_attrs)

        self.widget = widget

        # Increase the creation counter, and save our local copy.
        self.creation_counter = Field.creation_counter
        Field.creation_counter += 1

        messages = {}
        for c in reversed(self.__class__.__mro__):
            messages.update(getattr(c, 'default_error_messages', {}))
        messages.update(error_messages or {})
        self.error_messages = messages

        self.validators = self.default_validators + validators
Пример #2
0
def get_formats():
    """
    Returns all formats strings required for i18n to work
    """
    FORMAT_SETTINGS = ('DATE_FORMAT', 'DATETIME_FORMAT', 'TIME_FORMAT',
                       'YEAR_MONTH_FORMAT', 'MONTH_DAY_FORMAT',
                       'SHORT_DATE_FORMAT', 'SHORT_DATETIME_FORMAT',
                       'FIRST_DAY_OF_WEEK', 'DECIMAL_SEPARATOR',
                       'THOUSAND_SEPARATOR', 'NUMBER_GROUPING',
                       'DATE_INPUT_FORMATS', 'TIME_INPUT_FORMATS',
                       'DATETIME_INPUT_FORMATS')
    result = {}
    for module in [settings] + get_format_modules(reverse=True):
        for attr in FORMAT_SETTINGS:
            result[attr] = get_format(attr)
    src = []
    for k, v in result.items():
        if isinstance(v, (basestring, int)):
            src.append(
                "formats['%s'] = '%s';\n" %
                (javascript_quote(k), javascript_quote(smart_unicode(v))))
        elif isinstance(v, (tuple, list)):
            v = [javascript_quote(smart_unicode(value)) for value in v]
            src.append("formats['%s'] = ['%s'];\n" %
                       (javascript_quote(k), "', '".join(v)))
    return ''.join(src)
Пример #3
0
 def end_object(self, obj):
     self.objects.append({
         "model":
         smart_unicode(obj._meta),
         "pk":
         smart_unicode(obj._get_pk_val(), strings_only=True),
         "fields":
         self._current
     })
     self._current = None
 def _auto_id(self):
     """
     Calculates and returns the ID attribute for this BoundField, if the
     associated Form has specified auto_id. Returns an empty string otherwise.
     """
     auto_id = self.form.auto_id
     if auto_id and '%s' in smart_unicode(auto_id):
         return smart_unicode(auto_id) % self.html_name
     elif auto_id:
         return self.html_name
     return ''
 def valid_value(self, value):
     "Check to see if the provided value is a valid choice"
     for k, v in self.choices:
         if isinstance(v, (list, tuple)):
             # This is an optgroup, so look inside the group for options
             for k2, v2 in v:
                 if value == smart_unicode(k2):
                     return True
         else:
             if value == smart_unicode(k):
                 return True
     return False
 def clear_dir(self, path):
     """
     Deletes the given relative path using the destinatin storage backend.
     """
     dirs, files = self.storage.listdir(path)
     for f in files:
         fpath = os.path.join(path, f)
         if self.dry_run:
             self.log(u"Pretending to delete '%s'" % smart_unicode(fpath),
                      level=1)
         else:
             self.log(u"Deleting '%s'" % smart_unicode(fpath), level=1)
             self.storage.delete(fpath)
     for d in dirs:
         self.clear_dir(os.path.join(path, d))
 def handle_label(self, path, **options):
     verbosity = int(options.get('verbosity', 1))
     result = finders.find(path, all=options['all'])
     path = smart_unicode(path)
     if result:
         if not isinstance(result, (list, tuple)):
             result = [result]
         output = u'\n  '.join(
             (smart_unicode(os.path.realpath(path)) for path in result))
         self.stdout.write(
             smart_str(u"Found '%s' here:\n  %s\n" % (path, output)))
     else:
         if verbosity >= 1:
             self.stderr.write(
                 smart_str("No matching file found for '%s'.\n" % path))
 def choices(self, cl):
     from my_django.contrib.admin.views.main import EMPTY_CHANGELIST_VALUE
     yield {
         'selected':
         self.lookup_val is None and not self.lookup_val_isnull,
         'query_string':
         cl.get_query_string({},
                             [self.lookup_kwarg, self.lookup_kwarg_isnull]),
         'display':
         _('All'),
     }
     for pk_val, val in self.lookup_choices:
         yield {
             'selected':
             self.lookup_val == smart_unicode(pk_val),
             'query_string':
             cl.get_query_string({
                 self.lookup_kwarg: pk_val,
             }, [self.lookup_kwarg_isnull]),
             'display':
             val,
         }
     if (isinstance(self.field, models.related.RelatedObject)
             and self.field.field.null
             or hasattr(self.field, 'rel') and self.field.null):
         yield {
             'selected':
             bool(self.lookup_val_isnull),
             'query_string':
             cl.get_query_string({
                 self.lookup_kwarg_isnull: 'True',
             }, [self.lookup_kwarg]),
             'display':
             EMPTY_CHANGELIST_VALUE,
         }
Пример #9
0
 def m2m_convert(value):
     if hasattr(value, '__iter__'):
         return field.rel.to._default_manager.db_manager(
             db).get_by_natural_key(*value).pk
     else:
         return smart_unicode(
             field.rel.to._meta.pk.to_python(value))
 def label_from_instance(self, obj):
     """
     This method is used to convert objects into strings; it's used to
     generate the labels for the choices presented by this object. Subclasses
     can override this method to customize the display of the choices.
     """
     return smart_unicode(obj)
Пример #11
0
 def contents(self):
     from my_django.contrib.admin.templatetags.admin_list import _boolean_icon
     from my_django.contrib.admin.views.main import EMPTY_CHANGELIST_VALUE
     field, obj, model_admin = self.field['field'], self.form.instance, self.model_admin
     try:
         f, attr, value = lookup_field(field, obj, model_admin)
     except (AttributeError, ValueError, ObjectDoesNotExist):
         result_repr = EMPTY_CHANGELIST_VALUE
     else:
         if f is None:
             boolean = getattr(attr, "boolean", False)
             if boolean:
                 result_repr = _boolean_icon(value)
             else:
                 result_repr = smart_unicode(value)
                 if getattr(attr, "allow_tags", False):
                     result_repr = mark_safe(result_repr)
         else:
             if value is None:
                 result_repr = EMPTY_CHANGELIST_VALUE
             elif isinstance(f.rel, ManyToManyRel):
                 result_repr = ", ".join(map(unicode, value.all()))
             else:
                 result_repr = display_for_field(value, f)
     return conditional_escape(result_repr)
 def urls(self):
     "Returns a list of (value, URL) tuples."
     # First, check the urls() method for each plugin.
     plugin_urls = []
     for plugin_name, plugin in self.model.model_databrowse().plugins.items():
         urls = plugin.urls(plugin_name, self)
         if urls is not None:
             #plugin_urls.append(urls)
             values = self.values()
             return zip(self.values(), urls)
     if self.field.rel:
         m = EasyModel(self.model.site, self.field.rel.to)
         if self.field.rel.to in self.model.model_list:
             lst = []
             for value in self.values():
                 if value is None:
                     continue
                 url = mark_safe('%s%s/%s/objects/%s/' % (self.model.site.root_url, m.model._meta.app_label, m.model._meta.module_name, iri_to_uri(value._get_pk_val())))
                 lst.append((smart_unicode(value), url))
         else:
             lst = [(value, None) for value in self.values()]
     elif self.field.choices:
         lst = []
         for value in self.values():
             url = mark_safe('%s%s/%s/fields/%s/%s/' % (self.model.site.root_url, self.model.model._meta.app_label, self.model.model._meta.module_name, self.field.name, iri_to_uri(self.raw_value)))
             lst.append((value, url))
     elif isinstance(self.field, models.URLField):
         val = self.values()[0]
         lst = [(val, iri_to_uri(val))]
     else:
         lst = [(self.values()[0], None)]
     return lst
Пример #13
0
 def get_choices(self, include_blank=True, blank_choice=BLANK_CHOICE_DASH):
     """Returns choices with a default blank choices included, for use
     as SelectField choices for this field."""
     first_choice = include_blank and blank_choice or []
     if self.choices:
         return first_choice + list(self.choices)
     rel_model = self.rel.to
     if hasattr(self.rel, 'get_related_field'):
         lst = [(getattr(x, self.rel.get_related_field().attname),
                     smart_unicode(x))
                for x in rel_model._default_manager.complex_filter(
                    self.rel.limit_choices_to)]
     else:
         lst = [(x._get_pk_val(), smart_unicode(x))
                for x in rel_model._default_manager.complex_filter(
                    self.rel.limit_choices_to)]
     return first_choice + lst
 def clean(self, value):
     super(USPhoneNumberField, self).clean(value)
     if value in EMPTY_VALUES:
         return u''
     value = re.sub('(\(|\)|\s+)', '', smart_unicode(value))
     m = phone_digits_re.search(value)
     if m:
         return u'%s-%s-%s' % (m.group(1), m.group(2), m.group(3))
     raise ValidationError(self.error_messages['invalid'])
Пример #15
0
 def handle_m2m(value):
     natural = value.natural_key()
     # Iterable natural keys are rolled out as subelements
     self.xml.startElement("object", {})
     for key_value in natural:
         self.xml.startElement("natural", {})
         self.xml.characters(smart_unicode(key_value))
         self.xml.endElement("natural")
     self.xml.endElement("object")
Пример #16
0
 def log_action(self,
                user_id,
                content_type_id,
                object_id,
                object_repr,
                action_flag,
                change_message=''):
     e = self.model(None, None, user_id, content_type_id,
                    smart_unicode(object_id), object_repr[:200],
                    action_flag, change_message)
     e.save()
Пример #17
0
 def _start_relational_field(self, field):
     """
     Helper to output the <field> element for relational fields
     """
     self.indent(2)
     self.xml.startElement(
         "field", {
             "name": field.name,
             "rel": field.rel.__class__.__name__,
             "to": smart_unicode(field.rel.to._meta),
         })
Пример #18
0
 def handle_m2m_field(self, obj, field):
     if field.rel.through._meta.auto_created:
         if self.use_natural_keys and hasattr(field.rel.to, 'natural_key'):
             m2m_value = lambda value: value.natural_key()
         else:
             m2m_value = lambda value: smart_unicode(value._get_pk_val(),
                                                     strings_only=True)
         self._current[field.name] = [
             m2m_value(related)
             for related in getattr(obj, field.name).iterator()
         ]
Пример #19
0
    def start_object(self, obj):
        """
        Called as each object is handled.
        """
        if not hasattr(obj, "_meta"):
            raise base.SerializationError(
                "Non-model object (%s) encountered during serialization" %
                type(obj))

        self.indent(1)
        obj_pk = obj._get_pk_val()
        if obj_pk is None:
            attrs = {
                "model": smart_unicode(obj._meta),
            }
        else:
            attrs = {
                "pk": smart_unicode(obj._get_pk_val()),
                "model": smart_unicode(obj._meta),
            }

        self.xml.startElement("object", attrs)
 def choices(self, cl):
     yield {
         'selected': self.lookup_val is None,
         'query_string': cl.get_query_string({}, [self.lookup_kwarg]),
         'display': _('All')
     }
     for lookup, title in self.field.flatchoices:
         yield {
             'selected': smart_unicode(lookup) == self.lookup_val,
             'query_string':
             cl.get_query_string({self.lookup_kwarg: lookup}),
             'display': title,
         }
Пример #21
0
 def handle_fk_field(self, obj, field):
     """
     Called to handle a ForeignKey (we need to treat them slightly
     differently from regular fields).
     """
     self._start_relational_field(field)
     related_att = getattr(obj, field.get_attname())
     if related_att is not None:
         if self.use_natural_keys and hasattr(field.rel.to, 'natural_key'):
             related = getattr(obj, field.name)
             # If related object has a natural key, use it
             related = related.natural_key()
             # Iterable natural keys are rolled out as subelements
             for key_value in related:
                 self.xml.startElement("natural", {})
                 self.xml.characters(smart_unicode(key_value))
                 self.xml.endElement("natural")
         else:
             self.xml.characters(smart_unicode(related_att))
     else:
         self.xml.addQuickElement("None")
     self.xml.endElement("field")
Пример #22
0
 def __init__(self,
              template_string,
              origin=None,
              name='<Unknown Template>'):
     try:
         template_string = smart_unicode(template_string)
     except UnicodeDecodeError:
         raise TemplateEncodingError("Templates can only be constructed "
                                     "from unicode or UTF-8 strings.")
     if settings.TEMPLATE_DEBUG and origin is None:
         origin = StringOrigin(template_string)
     self.nodelist = compile_string(template_string, origin)
     self.name = name
    def clean(self, value):
        super(NLPhoneNumberField, self).clean(value)
        if value in EMPTY_VALUES:
            return u''

        phone_nr = re.sub('[\-\s\(\)]', '', smart_unicode(value))

        if len(phone_nr) == 10 and numeric_re.search(phone_nr):
            return value

        if phone_nr[:3] == '+31' and len(phone_nr) == 12 and \
           numeric_re.search(phone_nr[3:]):
            return value

        raise ValidationError(self.error_messages['invalid'])
 def __call__(self, value):
     try:
         super(URLValidator, self).__call__(value)
     except ValidationError, e:
         # Trivial case failed. Try for possible IDN domain
         if value:
             value = smart_unicode(value)
             scheme, netloc, path, query, fragment = urlparse.urlsplit(value)
             try:
                 netloc = netloc.encode('idna') # IDN -> ACE
             except UnicodeError: # invalid domain part
                 raise e
             url = urlparse.urlunsplit((scheme, netloc, path, query, fragment))
             super(URLValidator, self).__call__(url)
         else:
             raise
Пример #25
0
    def get_choices(self,
                    include_blank=True,
                    blank_choice=BLANK_CHOICE_DASH,
                    limit_to_currently_related=False):
        """Returns choices with a default blank choices included, for use
        as SelectField choices for this field.

        Analogue of my_django.db.models.fields.Field.get_choices, provided
        initially for utilisation by RelatedFieldListFilter.
        """
        first_choice = include_blank and blank_choice or []
        queryset = self.model._default_manager.all()
        if limit_to_currently_related:
            queryset = queryset.complex_filter(
                {'%s__isnull' % self.parent_model._meta.module_name: False})
        lst = [(x._get_pk_val(), smart_unicode(x)) for x in queryset]
        return first_choice + lst
 def get_for_models(self, *models):
     """
     Given *models, returns a dictionary mapping {model: content_type}.
     """
     # Final results
     results = {}
     # models that aren't already in the cache
     needed_app_labels = set()
     needed_models = set()
     needed_opts = set()
     for model in models:
         opts = self._get_opts(model)
         try:
             ct = self._get_from_cache(opts)
         except KeyError:
             needed_app_labels.add(opts.app_label)
             needed_models.add(opts.object_name.lower())
             needed_opts.add(opts)
         else:
             results[model] = ct
     if needed_opts:
         cts = self.filter(
             app_label__in=needed_app_labels,
             model__in=needed_models
         )
         for ct in cts:
             model = ct.model_class()
             if model._meta in needed_opts:
                 results[model] = ct
                 needed_opts.remove(model._meta)
             self._add_to_cache(self.db, ct)
     for opts in needed_opts:
         # These weren't in the cache, or the DB, create them.
         ct = self.create(
             app_label=opts.app_label,
             model=opts.object_name.lower(),
             name=smart_unicode(opts.verbose_name_raw),
         )
         self._add_to_cache(self.db, ct)
         results[ct.model_class()] = ct
     return results
    def get_for_model(self, model):
        """
        Returns the ContentType object for a given model, creating the
        ContentType if necessary. Lookups are cached so that subsequent lookups
        for the same model don't hit the database.
        """
        opts = self._get_opts(model)
        try:
            ct = self._get_from_cache(opts)
        except KeyError:
            # Load or create the ContentType entry. The smart_unicode() is
            # needed around opts.verbose_name_raw because name_raw might be a
            # django.utils.functional.__proxy__ object.
            ct, created = self.get_or_create(
                app_label = opts.app_label,
                model = opts.object_name.lower(),
                defaults = {'name': smart_unicode(opts.verbose_name_raw)},
            )
            self._add_to_cache(self.db, ct)

        return ct
Пример #28
0
    def last_executed_query(self, cursor, sql, params):
        """
        Returns a string of the query last executed by the given cursor, with
        placeholders replaced with actual values.

        `sql` is the raw query containing placeholders, and `params` is the
        sequence of parameters. These are used by default, but this method
        exists for database backends to provide a better implementation
        according to their own quoting schemes.
        """
        from my_django.utils.encoding import smart_unicode, force_unicode

        # Convert params to contain Unicode values.
        to_unicode = lambda s: force_unicode(
            s, strings_only=True, errors='replace')
        if isinstance(params, (list, tuple)):
            u_params = tuple([to_unicode(val) for val in params])
        else:
            u_params = dict([(to_unicode(k), to_unicode(v))
                             for k, v in params.items()])

        return smart_unicode(sql) % u_params
 def choices(self, cl):
     from my_django.contrib.admin.views.main import EMPTY_CHANGELIST_VALUE
     yield {
         'selected': (self.lookup_val is None
                      and self.lookup_val_isnull is None),
         'query_string':
         cl.get_query_string({},
                             [self.lookup_kwarg, self.lookup_kwarg_isnull]),
         'display':
         _('All'),
     }
     include_none = False
     for val in self.lookup_choices:
         if val is None:
             include_none = True
             continue
         val = smart_unicode(val)
         yield {
             'selected':
             self.lookup_val == val,
             'query_string':
             cl.get_query_string({
                 self.lookup_kwarg: val,
             }, [self.lookup_kwarg_isnull]),
             'display':
             val,
         }
     if include_none:
         yield {
             'selected':
             bool(self.lookup_val_isnull),
             'query_string':
             cl.get_query_string({
                 self.lookup_kwarg_isnull: 'True',
             }, [self.lookup_kwarg]),
             'display':
             EMPTY_CHANGELIST_VALUE,
         }
Пример #30
0
    def get_query_set(self, context):
        ctype, object_pk = self.get_target_ctype_pk(context)
        if not object_pk:
            return self.comment_model.objects.none()

        qs = self.comment_model.objects.filter(
            content_type=ctype,
            object_pk=smart_unicode(object_pk),
            site__pk=settings.SITE_ID,
        )

        # The is_public and is_removed fields are implementation details of the
        # built-in comment model's spam filtering system, so they might not
        # be present on a custom comment model subclass. If they exist, we
        # should filter on them.
        field_names = [f.name for f in self.comment_model._meta.fields]
        if 'is_public' in field_names:
            qs = qs.filter(is_public=True)
        if getattr(settings, 'COMMENTS_HIDE_REMOVED',
                   True) and 'is_removed' in field_names:
            qs = qs.filter(is_removed=False)

        return qs