def __init__(self, *args, **kwargs): kwargs.setdefault('max_length', 7) kwargs.setdefault('choices', [(k, translation.ugettext(v)) for k, v in settings.LANGUAGES]) add_introspection_rules([], ["^languages\.fields\.LanguageField"]) super(LanguageField, self).__init__(*args, **kwargs)
def try_initialize_south(): try: import south except ImportError: # No south in pypath return from south.modelsinspector import add_introspection_rules add_introspection_rules([], ["^current_user\.models\.CurrentUserField"])
def register_south_field(field_class): # make the fields work in South from south.modelsinspector import add_introspection_rules module = field_class.__module__ regex = r'^%s\.%s' % (re.escape(module), field_class.__name__) add_introspection_rules([], [regex]) return field_class
def try_initialize_south(): try: import south except ImportError: # No south in pypath return from south.modelsinspector import add_introspection_rules add_introspection_rules([], ["^historical\.models\.HistoricalForeignKey"]) add_introspection_rules([], ["^historical\.models\.KeyToHistoryMarker"])
def add_to_introspection_rule(self): try: from south.modelsinspector import add_introspection_rules except ImportError: pass else: add_introspection_rules( [([JsonDataField], [], {}), ], ["^gtoolkit\.db\.fields\.JsonDataField"])
def add_south_rules(): from south.modelsinspector import add_introspection_rules add_introspection_rules([ ( (VersionField,), [], {'partial': ('partial', {'default': False})}, ), ], ["semantic_version\.django_fields"])
def add_south_rules(): from south.modelsinspector import add_introspection_rules add_introspection_rules([ ( (VersionField,), [], {}, ), ], ["whatsnew\.fields"])
def load_object_field(): try: from south.modelsinspector import add_introspection_rules except ImportError: pass else: add_introspection_rules( [([ObjectField], [], {}),], ["^gtoolkit\.db\.fields\.ObjectField"]) add_introspection_rules( [([UniqueIDField], [], {}),], ["^gtoolkit\.db\.fields\.UniqueIDField"])
def ready(self): from south.modelsinspector import add_introspection_rules add_introspection_rules([], ["^markupfield\.fields\.MarkupField"]) # ping_details = {'blogango_details': pingback_blog_handler} from pingback import register_pingback, ping_func from . import pingback_blog_handler from django_xmlrpc import xmlrpcdispatcher register_pingback('blogango.views.details', pingback_blog_handler) xmlrpcdispatcher.register_function(ping_func, 'pingback.ping')
def add_south_introspector_rules(): from south.modelsinspector import add_introspection_rules rules = [ ( (StateFlowField, ), [], { "flow": ["flow_path", {}], } ), ] add_introspection_rules(rules, ["^stateflow\.statefields"])
def try_initialize_south(): try: import south except ImportError: # No south in pypath return from south.modelsinspector import add_introspection_rules from .fields import DictionaryField rules = [( (DictionaryField,), [], { 'type': ['type', {}], # 'render_pattern': ['render_pattern', {'default', None}], }, )] add_introspection_rules(rules, ["^django_dict\.fields\.DictionaryField"])
class DeferAutoOneToOneField(fields.AutoOneToOneField): def __init__(self, *args, **kwargs): self.defer_fields = list(kwargs.pop("defer_fields", [])) super(DeferAutoOneToOneField, self).__init__(*args, **kwargs) def contribute_to_related_class(self, cls, related): setattr( cls, related.get_accessor_name(), DeferAutoSingleRelatedObjectDescriptor(self.defer_fields, related)) if SOUTH: add_introspection_rules([( (DeferAutoOneToOneField, ), [], { "to": ["rel.to", {}], "to_field": ["rel.field_name", { "default_attr": "rel.to._meta.pk.name" }], "related_name": ["rel.related_name", { "default": None }], "db_index": ["db_index", { "default": True }], }, )], ["^inboxen\.fields\.DeferAutoOneToOneField"])
if isinstance(value, dict) or isinstance(value, list): value = json.dumps(value, cls=DjangoJSONEncoder) return super(JSONField, self).get_prep_value(value) def value_to_string(self, obj): """ Called by the serializer. """ value = self._get_val_from_obj(obj) return self.get_db_prep_value(value) try: from south.modelsinspector import add_introspection_rules add_introspection_rules([], ["^boundaryservice\.fields\.JSONField"]) add_introspection_rules([ ( [ListField], [], { "separator": ["separator", {"default": ","}], }, ), ], ["^boundaryservice\.fields\.ListField"]) except ImportError: pass
"we give the wrapped object back because we're not dealing with serialization types" return_val = LDObject.fromDict( parsed_value, type_hint=self.type_hint).wrapped_obj return return_val else: return None def get_prep_value(self, value, *args, **kwargs): """Convert our JSON object to a string before we save""" if isinstance(value, basestring): return value if value == None: return None # instantiate the proper LDObject to dump it appropriately ld_object = LDObject.instantiate(value, datatype=self.type_hint) return ld_object.serialize() def value_to_string(self, obj, *args, **kwargs): value = self._get_val_from_obj(obj) return self.get_prep_value(value, *args, **kwargs) ## ## for schema migration, we have to tell South about JSONField ## basically that it's the same as its parent class ## from south.modelsinspector import add_introspection_rules add_introspection_rules([], ["^helios\.datatypes\.djangofield.LDObjectField"])
if self.has_default(): if callable(self.default): return self.default() return copy.deepcopy(self.default) # If the field doesn't have a default, then we punt to models.Field. return super(JSONFieldBase, self).get_default() class JSONField(JSONFieldBase, models.TextField): """JSONField is a generic textfield that serializes/deserializes JSON objects""" form_class = JSONFormField def dumps_for_display(self, value): kwargs = {"indent": 2} kwargs.update(self.dump_kwargs) return json.dumps(value, ensure_ascii=False, **kwargs) class JSONCharField(JSONFieldBase, models.CharField): """JSONCharField is a generic textfield that serializes/deserializes JSON objects, stored in the database like a CharField, which enables it to be used e.g. in unique keys""" form_class = JSONCharFormField try: from south.modelsinspector import add_introspection_rules add_introspection_rules([], ["^jsonfield\.fields\.(JSONField|JSONCharField)"]) except ImportError: pass
class FieldFile(FieldFileMixin, BaseFieldFile): pass class FileField(FileFieldMixin, BaseFileField): attr_class = FieldFile add_introspection_rules([( (FileField, ), [], { 'private': ['private', {}], 'attachment': ['attachment', {}], 'content_types': ['content_types', {}], 'max_upload_size': ['max_upload_size', {}], 'strong_caching': ['strong_caching', {}], 'path_generator': ['path_generator', {}], 'contents_generator': ['original_contents_generator', {}], # These args accept a callable and therefore can # not be included in south introspection rules: # attachment_filename, condition, upload_to. }, )], ["^varnish_bans_manager\.filesystem\.models\.FileField"]) ############################################################################### class ImageFieldFile(FieldFileMixin, BaseImageFieldFile): """ Adds our custom mixin as well as support for resizing the image if it
# Arezqui Belaid <*****@*****.**> # from django.db import models from django.db.models.signals import post_save from django.utils.translation import ugettext_lazy as _ from django.contrib.contenttypes.models import ContentType from dialer_campaign.models import Campaign from dialer_cdr.models import Callrequest from survey.constants import SECTION_TYPE from audiofield.models import AudioFile, AudioField from django_lets_go.language_field import LanguageField from adminsortable.models import Sortable from south.modelsinspector import add_introspection_rules add_introspection_rules([], ["^common\.language_field\.LanguageField"]) add_introspection_rules([], ["^audiofield\.fields\.AudioField"]) add_introspection_rules( [ ( [AudioField], # Class(es) these apply to [], # Positional arguments (not used) { "ext_whitelist": ["ext_whitelist", { "default": "" }], }, # Keyword argument ), ], ["^audiofield\.fields\.AudioField"])
from collections import defaultdict from StringIO import StringIO from xml.etree.ElementTree import Element, SubElement, Comment, tostring from lxml import etree from django.db import models from django.contrib.auth.models import User from mongoengine.queryset import OperationError import vendor.opml as opml from apps.rss_feeds.models import Feed, DuplicateFeed, MStarredStory from apps.reader.models import UserSubscription, UserSubscriptionFolders from utils import json_functions as json, urlnorm from utils import log as logging from utils.feed_functions import timelimit from south.modelsinspector import add_introspection_rules add_introspection_rules([], ["^oauth2client\.django_orm\.FlowField"]) add_introspection_rules([], ["^oauth2client\.django_orm\.CredentialsField"]) class OAuthToken(models.Model): user = models.OneToOneField(User, null=True, blank=True) session_id = models.CharField(max_length=50, null=True, blank=True) uuid = models.CharField(max_length=50, null=True, blank=True) remote_ip = models.CharField(max_length=50, null=True, blank=True) request_token = models.CharField(max_length=50) request_token_secret = models.CharField(max_length=50) access_token = models.CharField(max_length=50) access_token_secret = models.CharField(max_length=50) credential = models.TextField(null=True, blank=True) created_date = models.DateTimeField(default=datetime.datetime.now)
dispatch_uid="create_team_and_keys_for_project", weak=False, ) post_save.connect( create_team_member_for_owner, sender=Team, dispatch_uid="create_team_member_for_owner", weak=False, ) post_save.connect( update_document, sender=Group, dispatch_uid="update_document", weak=False, ) post_save.connect( create_key_for_team_member, sender=TeamMember, dispatch_uid="create_key_for_team_member", weak=False, ) pre_delete.connect( remove_key_for_team_member, sender=TeamMember, dispatch_uid="remove_key_for_team_member", weak=False, ) user_logged_in.connect(set_language_on_logon) add_introspection_rules([], ["^social_auth\.fields\.JSONField"])
elif self.format == FORMAT_RGBA: regex = re.compile( "rgba\((?P<r>\d{1,3}),(?P<g>\d{1,3}),(?P<b>\d{1,3}),(?P<a>(0\.\d+)|\d)\)", re.IGNORECASE | re.UNICODE) is_valid = is_valid_rgba elif format == FORMAT_HEXA: regex = re.compile("#([A-Fa-f\d]{8}|[A-Fa-f\d]{6}|[A-Fa-f\d]{3})", re.IGNORECASE | re.UNICODE) is_valid = is_valid_alpha_hex else: regex = re.compile("#([A-Fa-f\d]{8}|[A-Fa-f\d]{6}|[A-Fa-f\d]{3})", re.IGNORECASE | re.UNICODE) is_valid = is_valid_hex if len(regex.findall(value)) != 1: raise ValidationError(invalid) if not is_valid(value): raise ValidationError(invalid) return super(ColorField, self).clean(value, model_instance) try: from south.modelsinspector import add_introspection_rules add_introspection_rules([], ["^colorpicker\.models\.ColorField"]) except ImportError: pass
By default this field will assume that your primary keys are numeric, simply because this is the most common case. However, if you have a non-integer primary key, you can simply pass ``pk_indexable=False`` to the constructor, and Auditlog will fall back to using a non-indexed text based field for this model. Using this field will not automatically register the model for automatic logging. This is done so you can be more flexible with how you use this field. :param pk_indexable: Whether the primary key for this model is not an :py:class:`int` or :py:class:`long`. :type pk_indexable: bool """ def __init__(self, pk_indexable=True, **kwargs): kwargs['to'] = LogEntry if pk_indexable: kwargs['object_id_field'] = 'object_id' else: kwargs['object_id_field'] = 'object_pk' kwargs['content_type_field'] = 'content_type' super(AuditlogHistoryField, self).__init__(**kwargs) # South compatibility for AuditlogHistoryField try: from south.modelsinspector import add_introspection_rules add_introspection_rules([], ["^auditlog\.models\.AuditlogHistoryField"]) raise DeprecationWarning( "South support will be dropped in django-auditlog 0.4.0 or later.") except ImportError: pass
return self.profile class Learner(Role): pass class Mentor(Role): pass from south.modelsinspector import add_introspection_rules #@UnresolvedImport from django.contrib.gis.geos import Point, Polygon add_introspection_rules([], ["^django_extensions\.db\.fields"]) class LocativeModel(TimeStampedModel): point = PointField() altitude = models.FloatField(blank=True, null=True) accuracy = models.FloatField(blank=True, null=True) altitude_accuracy = models.FloatField(blank=True, null=True) objects = GeoManager() class Meta(TimeStampedModel.Meta): abstract = True def latlon(): #@NoSelf doc = """Returns the latitude/longitude pair as a dict for the API, etc.""" #@UnusedVariable
('WLF', _('Wallis and Futuna Islands')), ('ESH', _('Western Sahara')), ('YEM', _('Yemen')), ('ZMB', _('Zambia')), ('ZWE', _('Zimbabwe')), ) class CountryField(models.CharField): def __init__(self, *args, **kwargs): kwargs.setdefault('max_length', 3) kwargs.setdefault('choices', COUNTRIES) super(CountryField, self).__init__(*args, **kwargs) def get_internal_type(self): return "CharField" try: from south.modelsinspector import add_introspection_rules except ImportError: pass else: add_introspection_rules([ ( [CountryField], [], {}, ), ], ["^pykeg\.core\.fields\.CountryField"])
class PointField(GeometryField): geom_type = 'POINT' class MultiPointField(GeometryField): geom_type = 'MULTIPOINT' class LineStringField(GeometryField): geom_type = 'LINESTRING' class MultiLineStringField(GeometryField): geom_type = 'MULTILINESTRING' class PolygonField(GeometryField): geom_type = 'POLYGON' class MultiPolygonField(GeoJSONField): geom_type = 'MULTIPOLYGON' try: from south.modelsinspector import add_introspection_rules add_introspection_rules([], ["^djgeojson\.fields\.(GeoJSONField|GeometryField|GeometryCollectionField|PointField|MultiPointField|LineStringField|MultiLineStringField|PolygonField|MultiPolygonField)"]) except ImportError: pass
for item in self._data: value = FormValue() value.field_name = item['name'] value.value = item['value'] self.values.add(value) self._data = None class FormValue(models.Model): form_log = models.ForeignKey(FormLog, related_name='values') field_name = models.SlugField(_('field name'), max_length=255) if settings.VALUE_PICKLEFIELD: # use PickledObjectField if available because it preserves the # original data type value = PickledObjectField(_('value'), null=True, blank=True) else: # otherwise just use a TextField, with the drawback that # all values will just be stored as unicode strings, # but you can easily query the database for form results. value = models.TextField(_('value'), null=True, blank=True) def __unicode__(self): return u'%s = %s' % (self.field_name, self.value) if 'south' in django_settings.INSTALLED_APPS: from south.modelsinspector import add_introspection_rules add_introspection_rules([], ["^form_designer\.fields\..*"])
# Add south introspection for timezones.fields.TimeZoneField # # We do this here because django-timezone is long in the tooth and # they haven't fixed it there, yet. Need to do this before it gets # used. If we end up using TimeZoneField elsewhere, then we should # centralize this hack. # # See https://github.com/brosner/django-timezones/pull/19 from south.modelsinspector import add_introspection_rules add_introspection_rules(rules=[((TimeZoneField, ), [], { "max_length": ["max_length", { "default": MAX_TIMEZONE_LENGTH }], "default": ["default", { "default": settings.TIME_ZONE }], "choices": ["choices", { "default": zones.PRETTY_TIMEZONE_CHOICES }], })], patterns=["^timezones\.fields\."]) @auto_delete_files class Profile(ModelBase, SearchMixin): """Profile model for django users, get it with user.get_profile().""" user = models.OneToOneField(User, primary_key=True, verbose_name=_lazy(u'User')) name = models.CharField(max_length=255,
# We'll just introspect the _actual_ field. try: from south.modelsinspector import introspector field_class = self.__class__.__module__ + "." + self.__class__.__name__ args, kwargs = introspector(self) # That's our definition! kwargs.update({ 'start_query': repr(self.start_query), 'size_width': repr(self.size_width), 'size_height': repr(self.size_height), }) return ('django_ymap.fields.YmapCoord', args, kwargs) except ImportError: pass def deconstruct(self): name, path, args, kwargs = super(YmapCoord, self).deconstruct() if "start_query" in kwargs: del kwargs["start_query"] if 'size_width' in kwargs: del kwargs["size_width"] if 'size_height' in kwargs: del kwargs["size_height"] return name, path, args, kwargs try: from south.modelsinspector import add_introspection_rules add_introspection_rules([], ["^django_ymap\.fields\.YmapCoord"]) except ImportError: pass
error.""" if isinstance(value, six.string_types): super(JSONField, self).validate(value, model_instance) try: json.loads(value) except Exception as err: raise ValidationError(str(err)) def get_prep_value(self, value): """Convert value to JSON string before save""" try: return json.dumps(value) except Exception as err: raise ValidationError(str(err)) def value_to_string(self, obj): """Return value from object converted to string properly""" return smart_text(self.get_prep_value(self._get_val_from_obj(obj))) def value_from_object(self, obj): """Return value dumped to string.""" return self.get_prep_value(self._get_val_from_obj(obj)) try: from south.modelsinspector import add_introspection_rules add_introspection_rules( [], ["^social\.apps\.django_app\.default\.fields\.JSONField"]) except: pass
from django.db.models import FileField from django import forms from django.utils.translation import ugettext as _ import pyfits from specreduce.specreduce import OneDimensionalSpectrumValidator from specreduce.specreduce import ValidationError from south.modelsinspector import add_introspection_rules add_introspection_rules([], ["^spectra\.extra\.OneDimensionalSpectrumFileField"]) class OneDimensionalSpectrumFileField(FileField): def clean(self, *args, **kwargs): data = super(OneDimensionalSpectrumFileField, self).clean(*args, **kwargs) # This will raise IOError if there is a parse failure try: hdulist = pyfits.open(data.file) except IOError as e: raise forms.ValidationError(_('Unable to parse FITS file: %s' % e)) try: OneDimensionalSpectrumValidator(hdulist).validate() except ValidationError as e: raise forms.ValidationError(_('FITS validation failed: %s' % e)) return data
if value: try: setattr(kwargs['instance'], self.attname, self._deserialize(value)) except: setattr(kwargs['instance'], self.attname, 'a') else: setattr(kwargs['instance'], self.attname, None) try: from south.modelsinspector import add_introspection_rules add_introspection_rules( [ ( [SerializedObjectField], # Class(es) these apply to [], # Positional arguments (not used) { # Keyword argument "serialize_format": [ "serialize_format", {"default": "json"}], }, ), ], ["^moderation\.fields\.SerializedObjectField"] ) except ImportError: pass
if value is None or value == "": return None value = int(value, 16) # on postgres only, interpret as signed if connection.settings_dict["ENGINE"] in postgres_engines: value = struct.unpack("q", struct.pack("Q", value))[0] return value def to_python(self, value): if isinstance(value, six.string_types): return value if value is None: return "" # on postgres only, re-interpret from signed to unsigned if connection.settings_dict["ENGINE"] in postgres_engines: value = hex(struct.unpack("Q", struct.pack("q", value))[0]) return value def formfield(self, **kwargs): defaults = {"form_class": HexadecimalField} defaults.update(kwargs) # yes, that super call is right return super(models.IntegerField, self).formfield(**defaults) try: from south.modelsinspector import add_introspection_rules add_introspection_rules([], ["^push_notifications\.fields\.HexIntegerField"]) except ImportError: pass
value = super(SanitizedCharField, self).to_python(value) value = bleach.clean(value, tags=self._sanitizer_allowed_tags, attributes=self._sanitizer_allowed_attributes, strip=self._sanitizer_strip) return smart_unicode(value) class SanitizedTextField(models.TextField): def __init__(self, allowed_tags=None, allowed_attributes=None, strip=False, *args, **kwargs): self._sanitizer_allowed_tags = allowed_tags self._sanitizer_allowed_attributes = allowed_attributes self._sanitizer_strip = strip super(SanitizedTextField, self).__init__(*args, **kwargs) def to_python(self, value): value = super(SanitizedTextField, self).to_python(value) value = bleach.clean(value, tags=self._sanitizer_allowed_tags, attributes=self._sanitizer_allowed_attributes, strip=self._sanitizer_strip) return smart_unicode(value) def get_prep_value(self, value): value = super(SanitizedTextField, self).get_prep_value(value) value = bleach.clean(value, tags=self._sanitizer_allowed_tags, attributes=self._sanitizer_allowed_attributes, strip=self._sanitizer_strip) return value if 'south' in settings.INSTALLED_APPS: from south.modelsinspector import add_introspection_rules add_introspection_rules([], ["^sanitizer\.models\.SanitizedCharField"]) add_introspection_rules([], ["^sanitizer\.models\.SanitizedTextField"])
from fields import StdImageField try: from south.modelsinspector import add_introspection_rules rules = [ ( (StdImageField,), [], { "size": ["size", {"default": None}], "thumbnail_size": ["thumbnail_size", {"default": None}], "upload_to": ["upload_to", {"default": None}], }, ) ] add_introspection_rules(rules, ["^stdimage\.fields"]) except ImportError: pass
def to_python(self, value): #this is the value right out of the db, or an instance if isinstance(value, models.CharField): #if an instance, just return the instance return value if value==None: #if the db has a NULL (==None in Python) return "" #convert it into the Django-friendly '' string else: return value #otherwise, return just the value def get_db_prep_value(self, value, *args, **kwargs): #catches value right before sending to db if value=="": #if Django tries to save '' string, send the db None (NULL) return None else: return super(CharNullField, self).get_db_prep_value(value, *args, **kwargs) if 'south' in settings.INSTALLED_APPS: from south.modelsinspector import add_introspection_rules add_introspection_rules([], ["^ecwsp\.sis\.helper_functions\.CharNullField"]) class ReadPermissionModelAdmin(admin.ModelAdmin): """ based on http://gremu.net/blog/2010/django-admin-read-only-permission/ Admin model that allows users to read """ def has_change_permission(self, request, obj=None): if getattr(request, 'readonly', False): return True return super(ReadPermissionModelAdmin, self).has_change_permission(request, obj) def changelist_view(self, request, extra_context=None): try: return super(ReadPermissionModelAdmin, self).changelist_view( request, extra_context=extra_context) except PermissionDenied:
from __future__ import unicode_literals from .conf import settings try: from south.modelsinspector import add_introspection_rules add_introspection_rules([], ["^geoposition\.fields\.GeopositionField"]) except ImportError: pass
from django.db import models from django import forms from .widjets import AddressPickerWidget class AddressPickerField(models.CharField): def __init__(self, *args, **kwargs): super(AddressPickerField, self).__init__(*args, **kwargs) def formfield(self, **kwargs): defaults = { 'form_class': AddressPickerFormField, } defaults.update(kwargs) return super(AddressPickerField, self).formfield(**defaults) class AddressPickerFormField(forms.fields.CharField): def __init__(self, *args, **kwargs): kwargs.update({'widget': AddressPickerWidget()}) super(AddressPickerFormField, self).__init__(*args, **kwargs) try: from south.modelsinspector import add_introspection_rules add_introspection_rules([], ["^addresspicker\.fields\.AddressPickerField"]) except ImportError: pass
# -*- coding: utf-8 -*- from django.db.models import Field from django.conf import settings from .widgets import UiKitWidget class UiKitField(Field): def __init__(self, *args, **kwargs): mode = kwargs.pop('mode', 'split') markdown = kwargs.pop('markdown', False) self.widget = UiKitWidget( mode=mode, markdown=markdown, ) super(UiKitField, self).__init__(*args, **kwargs) def get_internal_type(self): return "TextField" def formfield(self, **kwargs): defaults = {'widget': self.widget} defaults.update(kwargs) return super(UiKitField, self).formfield(**defaults) if 'south' in settings.INSTALLED_APPS: from south.modelsinspector import add_introspection_rules add_introspection_rules([], ["^uikit_editor\.fields\.UiKitField"])
class MultiSiteField(models.ManyToManyField): def __init__(self, **kwargs): defaults = { 'blank': False, } defaults.update(kwargs) if 'to' in defaults: del defaults['to'] super(MultiSiteField, self).__init__(Site, **defaults) class SingleSiteField(models.ForeignKey): def __init__(self, **kwargs): if 'to' in kwargs: del kwargs['to'] super(SingleSiteField, self).__init__(Site, **kwargs) # Make sure South migrations work try: from south.modelsinspector import add_introspection_rules add_introspection_rules([], ["^begood_sites\.fields\.MultiSiteField"]) add_introspection_rules([], ["^begood_sites\.fields\.SingleSiteField"]) except: pass
def dumps_for_display(self, value): kwargs = {"indent": 2} kwargs.update(self.dump_kwargs) return json.dumps(value, **kwargs) class JSONCharField(JSONFieldBase, models.CharField): """JSONCharField is a generic textfield that serializes/deserializes JSON objects, stored in the database like a CharField, which enables it to be used e.g. in unique keys""" form_class = JSONCharFormField class JSONBinaryField(JSONFieldBase, models.BinaryField): """JSONBinaryField is a generic textfield that serializes/deserializes JSON objects, stored in the database like a BinaryField, which, in some databases, may allow for larger maximum field sizes.""" def get_db_prep_value(self, value, connection, prepared=False): """Convert JSON object to a string""" if self.null and value is None: return bytearray() return bytearray(json.dumps(value, **self.dump_kwargs), 'utf8') try: from south.modelsinspector import add_introspection_rules add_introspection_rules( [], ["^jsonfield\.fields\.(JSONField|JSONCharField|JSONBinaryField)"]) except ImportError: pass
# raise TypeError("Field has invalid lookup: %s" % lookup_type) def get_db_prep_lookup(self, lookup_type, value, connection, prepared=False): return self.get_prep_lookup(lookup_type, value) def get_prep_value(self, value): return value try: from south.modelsinspector import add_introspection_rules add_introspection_rules(rules=[], patterns=['djorm_pgfulltext\.fields\.VectorField']) except ImportError: pass if django.VERSION[:2] >= (1, 7): # Create custom lookups for Django>= 1.7 from django.db.models import Lookup def quotes(wordlist): return [ "%s" % adapt(x.replace("\\", "").encode('utf-8')) for x in wordlist ] def startswith(wordlist): return [x + ":*" for x in quotes(wordlist)]
from django.db import models from stdimage import StdImageField from south.modelsinspector import add_introspection_rules from django.contrib.auth.models import User from django.core.exceptions import ValidationError # Rules for South to migrate the custom StdImageField, don't touch rules = [ ( (StdImageField,), [], {"size": ["size", {"default": None}], "thumbnail_size": ["thumbnail_size", {"default": None}]}, ) ] add_introspection_rules(rules, ["^stdimage\.fields"]) class Dictionary(models.Model): subject = models.CharField(max_length=20) owner = models.ForeignKey(User) def __unicode__(self): return "%s" % (self.subject) class WordEntry(models.Model): PART_CHOICES = ( ("noun", "Noun"), ("verb", "Verb"), ("adjective", "Adjective"),
from django.db import models from tinymce.models import HTMLField from south.modelsinspector import add_introspection_rules add_introspection_rules([], ["^tinymce\.models\.HTMLField"]) # Create your models here. class Help(models.Model): heading = models.CharField(max_length=500) slug = models.SlugField(unique=True, db_index=True) help = HTMLField(blank=True)
field.help_text = "Enter valid YAML" return field def contribute_to_class(self, cls, name): super(YAMLCodeMirrorField, self).contribute_to_class(cls, name) def as_python(self): value = getattr(self, name) try: result = yaml.load(value) except (ValueError, AttributeError), e: log.debug("YAML to Python failed: {0}".format(e)) result = {} return result cls.add_to_class('{0}_as_python'.format(name), as_python) """ I need the field to... coerce to python normally BUT, on database save, I need the form input to go to the database verbatim. Not coerced to python, then converted to a string. """ try: from south.modelsinspector import add_introspection_rules add_introspection_rules([], [ "^codemirror\.fields\.JSONCodeMirrorField", "^codemirror\.fields\.YAMLCodeMirrorField",]) except: pass
('wa', _('Walloon')), ('wo', _('Wolof')), ('xh', _('Xhosa')), ('yi', _('Yiddish')), ('yo', _('Yoruba')), ('za', _('Zhuang; Chuang')), ('zh', _('Chinese')), ('zu', _('Zulu')), ) class LanguageField(models.CharField): """Stores language codes as defined by ISO 639-1""" description = _("Stores language codes") def __init__(self, *args, **kwargs): kwargs.setdefault('max_length', 2) kwargs.setdefault('choices', LANGUAGES) super(LanguageField, self).__init__(*args, **kwargs) def get_internal_type(self): return 'CharField' if _using_south: add_introspection_rules([], ['^djangomissing\.fields\.LanguageField']) # End of file
# reason: converting to dict then repr that dict in a form is invalid json # i.e. {"test": 0.5} becomes {u'test': 0.5} (not unicode and single quotes) return value def get_db_prep_save(self, value, *args, **kwargs): """Convert our JSON object to a string before we save""" if value == "": return None if isinstance(value, dict): value = json.dumps(value, cls=DjangoJSONEncoder) return super(JSONField, self).get_db_prep_save(value, *args, **kwargs) # http://south.readthedocs.org/en/latest/customfields.html#extending-introspection from south.modelsinspector import add_introspection_rules add_introspection_rules([], ["^seak\.models\.JSONField"]) class ConservationFeature(models.Model): ''' Django model representing Conservation Features (typically species) ''' name = models.CharField(max_length=99) level1 = models.CharField(max_length=99) level2 = models.CharField(max_length=99, null=True, blank=True) dbf_fieldname = models.CharField(max_length=15, null=True, blank=True) units = models.CharField(max_length=90, null=True, blank=True) desc = models.TextField(null=True, blank=True) uid = models.IntegerField(primary_key=True) @property def level_string(self):
'field': self.rel.field_name, 'value': value, 'pk': value, # included for backwards compatibility }) else: super(DynamicChoicesForeignKeyMixin, self).validate(value, model_instance) class DynamicChoicesForeignKey(DynamicChoicesForeignKeyMixin, ForeignKey): form_class = DynamicModelChoiceField class DynamicChoicesOneToOneField(DynamicChoicesForeignKeyMixin, OneToOneField): form_class = DynamicModelChoiceField class DynamicChoicesManyToManyField(DynamicChoicesField, ManyToManyField): form_class = DynamicModelMultipleChoiceField try: from south.modelsinspector import add_introspection_rules add_introspection_rules([], ['^dynamic_choices\.db\.models']) except ImportError: pass
""" The image field based on django-filebrowser, SORL thumbnail or any other image library. It's a drop-in replacement for the django :class:`~django.db.models.ImageField` When *django-filebrowser* is not installed, it will display the standard :class:`~django.db.models.ImageField` with a preview attached to it. """ def __init__(self, *args, **kwargs): # django-filebrowser has no concept of a 'width_field', # only Django's ImageField has this feature. if 'width_field' in kwargs: raise NotImplementedError("Unable to use 'width_field' in AnyImageField, not all backends support this feature.") if 'height_field' in kwargs: raise NotImplementedError("Unable to use 'height_field' in AnyImageField, not all backends support this feature.") super(AnyImageField, self).__init__(*args, **kwargs) # Tell South how to create custom fields try: from south.modelsinspector import add_introspection_rules add_introspection_rules([], [ "^any_imagefield\.models\.fields\.AnyFileField", "^any_imagefield\.models\.fields\.AnyImageField", "^any_imagefield\.models\.fields\.backends\.([^.]+)\.AnyFileField", "^any_imagefield\.models\.fields\.backends\.([^.]+)\.AnyImageField", ]) except ImportError: pass
}) return mark_safe(html) class SortedM2MFormField(sortedm2m.fields.SortedMultipleChoiceField): widget = SortedM2MWidget def __init__(self, *args, **kwargs): kwargs['widget'] = self.widget super(SortedM2MFormField, self).__init__(*args, **kwargs) class SortedM2MModelField(sortedm2m.fields.SortedManyToManyField): default_field_class = SortedM2MFormField def formfield(self, **kwargs): defaults = { 'form_class': self.default_field_class, } defaults.update(kwargs) return super(SortedM2MModelField, self).formfield(**defaults) try: from south.modelsinspector import add_introspection_rules add_introspection_rules( [], ["^aldryn_common\.admin_fields\.sortedm2m\.SortedM2MModelField"]) except: # If South not installed, then we really don't need to have done this. pass
self._dbtype = dbtype kwargs.setdefault('blank', True) kwargs.setdefault('null', True) kwargs.setdefault('default', None) super(GeometricField, self).__init__(*args, **kwargs) def db_type(self, connection): return self._dbtype.db_type(connection) def get_db_prep_value(self, value, connection, prepared=False): value = value if prepared else self.get_prep_value(value) return value def to_python(self, value): return value try: from south.modelsinspector import add_introspection_rules from .objects import Point add_introspection_rules([ ( [GeometricField], # class [], # positional params {'dbtype': ["_dbtype", {"default": Point}]}, # kwargs ) ], ['django_orm\.postgresql\.geometric\.fields\.GeometricField']) except ImportError: pass
return '' def get_configure(self): from merengue.theming.models import Theme return render_to_string( 'multimedia/audio.js', { 'audio_info': self, 'MEDIA_URL': settings.MEDIA_URL, 'THEME_MEDIA_URL': Theme.objects.active().get_theme_media_url() }) def save(self, **kwargs): self._save_original_filename(self.file) super(Audio, self).save(**kwargs) objects = WorkflowManager() # ----- adding south rules to help introspection ----- rules = [ ( (StdImageField, ), [], {}, ), ] add_introspection_rules(rules, ["^stdimage\.fields\.StdImageField"])
#operating_system= models.CharField(_('Operating system'), max_length=15) #ip_address = models.CharField(_('IP Address'), max_length=15) #backtrace = models.TextField(_('Python backtrace')) def delete_version_package(sender, instance, **kw): """ Removes the zip package """ try: os.remove(instance.package.path) except: pass def delete_plugin_icon(sender, instance, **kw): """ Removes the plugin icon """ try: os.remove(instance.icon.path) except: pass models.signals.post_delete.connect(delete_version_package, sender=PluginVersion) models.signals.post_delete.connect(delete_plugin_icon, sender=Plugin) from south.modelsinspector import add_introspection_rules add_introspection_rules([], ["^plugins\.models\.QGVersionZeroForcedField"]) add_introspection_rules([], ["^plugins\.models\.VersionField"])
from tagging.fields import TagField from organizations.models import Organization from managers import DecisionManager from custom_notification.utils import send_observation_notices_for # Ideally django-tinymce should be patched # http://south.aeracode.org/wiki/MyFieldsDontWork # http://code.google.com/p/django-tinymce/issues/detail?id=80 # TODO: Status codes could possibly be harvested off into its # own class with accessor methods to return values. from south.modelsinspector import add_introspection_rules add_introspection_rules([], ["^tagging\.fields\.TagField"]) class Decision(models.Model): TAGS_HELP_FIELD_TEXT = "Enter a list of tags separated by spaces." DISCUSSION_STATUS = 'discussion' PROPOSAL_STATUS = 'proposal' DECISION_STATUS = 'decision' ARCHIVED_STATUS = 'archived' STATUS_CHOICES = ( (DISCUSSION_STATUS, _('discussion')), (PROPOSAL_STATUS, _('proposal')), (DECISION_STATUS, _('decision')), (ARCHIVED_STATUS, _('archived')),
color_re = re.compile('^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$') validate_color = RegexValidator(color_re, _(u'Enter a valid color.'), 'invalid') class ColorWidget(forms.Widget): class Media: js = [settings.STATIC_URL + 'colorfield/jscolor.js'] def render(self, name, value, attrs=None): return render_to_string('colorfield/color.html', locals()) class ColorField(models.CharField): default_validators = [validate_color] def __init__(self, *args, **kwargs): kwargs['max_length'] = 10 super(ColorField, self).__init__(*args, **kwargs) def formfield(self, **kwargs): kwargs['widget'] = ColorWidget return super(ColorField, self).formfield(**kwargs) try: from south.modelsinspector import add_introspection_rules add_introspection_rules([], ["^colorfield\.fields\.ColorField"]) except ImportError: pass # vim: et sw=4 sts=4
return value.split(",") def contribute_to_class(self, cls, name): super(MultiSelectField, self).contribute_to_class(cls, name) if self.choices: func = lambda self, fieldname=name, choicedict=dict( self.choices): ",".join([ choicedict.get(value, value) for value in getattr(self, fieldname) ]) setattr(cls, 'get_%s_display' % self.name, func) def validate(self, value, model_instance): """ Extension to properly validate. """ assert self.choices, "Choices must be set." if value: # Make sure all values are in the acceptable set set_diff = set(value) - set([c[0] for c in self.choices]) if set_diff: raise ValidationError("Unrecognized choices: %s" % set_diff) # Bcipolli: I added this to make database migrations work. # # See: http://south.aeracode.org/wiki/MyFieldsDontWork from south.modelsinspector import add_introspection_rules add_introspection_rules([], ["^django_snippets\.multiselect\.MultiSelectField"])
from south.modelsinspector import add_introspection_rules from django.conf import settings if "tagging" in settings.INSTALLED_APPS: try: from tagging.fields import TagField except ImportError: pass else: rules = [ ( (TagField, ), [], { "blank": ["blank", {"default": True}], "max_length": ["max_length", {"default": 255}], }, ), ] add_introspection_rules(rules, ["^tagging\.fields",]) if "tagging_autocomplete" in settings.INSTALLED_APPS: add_introspection_rules([], ["^tagging_autocomplete\.models\.TagAutocompleteField"])
# JSON type only available in PostgreSQL >=9.2 if (connection.vendor == 'postgresql' and connection.pg_version >= 90200): return 'json' return 'text' def to_python(self, value): if hasattr(value, 'json_string') or value is None: return value return JSON(value) def get_prep_value(self, value): '''The psycopg adaptor returns Python objects, but we also have to handle conversion ourselves ''' if isinstance(value, JSON.JsonDict): return json.dumps(value, cls=JSON.Encoder) if isinstance(value, JSON.JsonList): return value.json_string if isinstance(value, JSON.JsonString): return json.dumps(value) return value # introspection rules to be compatible with south try: from south.modelsinspector import add_introspection_rules add_introspection_rules([], ['^unchained\.fields\.JSONField']) except ImportError: pass
else: data = unicode(val) return data def to_python(self, value): """ Returns a ``StringUUID`` instance from the value returned by the database. This doesn't use uuid.UUID directly for backwards compatibility, as ``StringUUID`` implements ``__unicode__`` with ``uuid.UUID.hex()``. """ if not value: return None # attempt to parse a UUID including cases in which value is a UUID # instance already to be able to get our StringUUID in. return StringUUID(smart_unicode(value), hyphenate=self.hyphenate) def formfield(self, **kwargs): defaults = { 'form_class': forms.CharField, 'max_length': self.max_length, } defaults.update(kwargs) return super(UUIDField, self).formfield(**defaults) try: from south.modelsinspector import add_introspection_rules add_introspection_rules([], ['^distributed\.fields\.UUIDField'],) except ImportError: pass
"""Models of the ``django_libs`` projects.""" from django.core.validators import RegexValidator from django.db.models import CharField from south.modelsinspector import add_introspection_rules from .widgets import ColorPickerWidget add_introspection_rules([], ["^django_libs\.models\.ColorField"]) class ColorField(CharField): """Custom color field to display a color picker.""" def __init__(self, *args, **kwargs): kwargs['max_length'] = 6 super(ColorField, self).__init__(*args, **kwargs) self.validators.append( RegexValidator( regex='^([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$', message='Only RGB color model inputs allowed, like 00000', code='nomatch')) def formfield(self, **kwargs): kwargs['widget'] = ColorPickerWidget return super(ColorField, self).formfield(**kwargs)
except AttributeError: return value # allow South to handle these fields smoothly try: from south.modelsinspector import add_introspection_rules # For a normal MarkupField, the add_excerpt_field attribute is # always True, which means no_excerpt_field arg will always be # True in a frozen MarkupField, which is what we want. add_introspection_rules(rules=[ ( (SplitField,), [], {'no_excerpt_field': ('add_excerpt_field', {})} ), ( (MonitorField,), [], {'monitor': ('monitor', {})} ), ( (StatusField,), [], {'no_check_for_status': ('check_for_status', {})} ), ], patterns=['model_utils\.fields\.']) except ImportError: pass
from django.db import models import os from imagekit.models import ImageModel from boto.s3.connection import S3Connection from boto.s3.key import Key from myproject import settings import random, string import s3storage from django.db.models.signals import post_save, post_init, pre_save, pre_delete from django.dispatch import receiver from django.contrib.auth.models import User from datetime import datetime from south.modelsinspector import add_introspection_rules add_introspection_rules([], ["^imager\.s3storage\.S3EnabledImageField"]) import uuid def get_file_path(instance, filename, **kwargs): filefolder = '%s' % (uuid.uuid4()) filename = kwargs.get('addendum', 'original') print os.path.join('images', filefolder, filename) return os.path.join('images', filefolder, filename) class Image(models.Model): image_file = s3storage.S3EnabledImageField(upload_to=get_file_path) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) height = models.IntegerField(editable=False, default=0)