class URLInspection(models.Model): created_at = models.DateTimeField(auto_now_add=True) url = models.TextField( blank=True, null=True ) # We may get (and want to store) really long or invalid urls, so... requested_url = models.TextField( ) # We may get (and want to store) really long or invalid urls, so... encoding = models.CharField(max_length=120, blank=True, null=True) apparent_encoding = models.CharField(max_length=120, blank=True, null=True) content = models.OneToOneField(ResponseContent, null=True, related_name='content_for', editable=False) history = hstore.ReferencesField(blank=True, null=True) parent = models.ForeignKey('self', blank=True, null=True, on_delete=models.SET_NULL) status_code = models.IntegerField(max_length=3, blank=True, null=True) reason = models.CharField( blank=True, null=True, max_length=80, help_text= 'Textual reason of responded HTTP Status, e.g. "Not Found" or "OK".') headers = hstore.DictionaryField(default=dictionary_default) timeout = models.BooleanField(default=False) probe = models.ForeignKey('Probe', null=True, blank=True, related_name='url_inspections') objects = URLInspectionManager.from_queryset(URLInspectionQuerySet)() class Meta: verbose_name = 'URL Inspection' verbose_name_plural = 'URL Inspections' get_latest_by = 'created_at' ordering = ('-created_at', 'requested_url') def __repr__(self): return '<URLInspection: {0} : {1}>'.format(self.requested_url, self.status_code) def __str__(self): return self.__repr__()
class Subscription(models.Model): customer = models.ForeignKey(Customer) plan = models.ForeignKey(Plan) metadata = hstore.DictionaryField(default={}, blank=True) stripe_id = models.CharField("Stripe subscription ID", max_length=255,\ blank=True, editable=False) status = models.CharField(max_length=32, choices=STATUS, default='active') def __unicode__(self): return '{}, {}'.format(self.customer, self.plan) def save(self, *args, **kwargs): stripe.api_key = base.SECRET_KEY try: customer = stripe.Customer.retrieve(self.customer.stripe_id) self.stripe_id = customer.subscriptions.create( plan=self.plan, metadata=self.metadata)\ .id except Exception as e: print '[!] Create subscription failed', e self.stripe_id = None if self.stripe_id: return super(Subscription, self).save(*args, **kwargs) def delete(self, *args, **kwargs): stripe.api_key = base.SECRET_KEY print 'Deleting...' print self.stripe_id print self.customer.stripe_id try: customer = stripe.Customer.retrieve(self.customer.stripe_id) subscription = customer.subscriptions.retrieve(self.stripe_id) result = subscription.delete() print 'result: ', result except Exception as e: print e result = None # if result: print 'Deleting from DB' return super(Subscription, self).delete(*args, **kwargs)
class NullSchemaDataBag(HStoreModel): name = models.CharField(max_length=32) data = hstore.DictionaryField(null=True, default=None, schema=[ { 'name': 'number', 'class': 'IntegerField', 'kwargs': { 'default': 1 } }, { 'name': 'char', 'class': 'CharField', 'kwargs': { 'default': 'test', 'blank': True, 'max_length': 10 } } ])
class PointOfInterest(HStoreModel): """ Extendable point of interest model """ created_at = djangomodels.DateTimeField(auto_now_add=True) updated_at = djangomodels.DateTimeField(auto_now=True) # can pass attributes like null, blank, etc. data = hstore.DictionaryField() location = djangomodels.ForeignKey(Location, related_name='location') def __unicode__(self): # This will only work while the data is well structured if "Clinic Name" in self.data: return "%s at %s, %s" % (self.data["Clinic Name"], self.location.point.x, self.location.point.y) else: return "Point of Interest at %s, %s" % \ (self.location.point.x, self.location.point.y)
class DataSource(models.Model): """Any of various data sources. Use meta to store extra info.""" source_type = models.CharField( choices=(('SATELLITE', 'Satellite data'), ('ADMIN', 'Admin boundaries'), ('ROADS', 'Roads'), ('HYDRO', 'Hydrography'), ('ELEVATION', 'Elevation'), ('SETTLEMENTS', 'Settlements'), ('HEALTH', 'Health facilities'), ('SCHOOLS', 'Schools'), ('SHELTER', 'Shelter'), ('POPULATION', 'Population'), ('IMPACT', 'Impact indicators/statistics'), ('NEEDS', 'Needs'), ('RESOURCING', 'Resourcing'), ('GENERAL', 'General')), max_length=20, ) name = models.CharField(max_length=255) meta = hstore.DictionaryField() def __unicode__(self): return "{0} - {1}".format(self.source_type, self.name)
class BaseModel(VoteModel): """ BaseModel An abstract base class with timestamps and votes. Stores data with HStore. """ data = hstore.DictionaryField(db_index=True) objects = Manager() class Meta: abstract = True def get(self, key): try: return self.data[key] except: return None def get_absolute_url(self): return reverse("content_detail", args=[self.__class__.__name__, self.id, self.get("slug")])
class EmailManagement(models.Model): token = models.CharField(max_length=64, primary_key=True) customer = models.ForeignKey(Customer, on_delete=models.deletion.SET_NULL, related_name='%(class)ss', null=True, blank=True) action = hstore.DictionaryField(default={}) active = models.BooleanField(default=True) order = models.ForeignKey(Order, on_delete=models.deletion.SET_NULL, related_name='%(class)ss', blank=True, null=True) objects = hstore.HStoreManager() def __unicode__(self): return '{} [{}]'.format(self.customer.user.email, self.order.id if self.order else ' - ')
class Microarray(models.Model): must_have_attributes = ['accession', 'name'] data = hstore.DictionaryField(db_index=True, blank=True) objects = hstore.HStoreManager() def _show(self): to_print = 'name' if to_print in self.data: return str(self.data[to_print]) else: return str(self.id) def __unicode__(self): return self._show() def __str__(self): return self._show() def __repr__(self): return self._show() def add_or_replace(data): obj, some_bool = Microarray.objects.get_or_create( data__contains={'accession': data['accession']}) obj.data = data obj.save() return obj def to_dict(self): d = {} for item in Microarray.must_have_attributes: d[item] = str(self.data[item]) return d def to_list_of_dicts(): arrays = Microarray.objects.all() list_of_dicts = [] for array in arrays: list_of_dicts.append(array.to_dict()) return list_of_dicts
class StandardName(ShowModel): """ """ name = models.CharField(max_length=255) additional_info = hstore.DictionaryField(db_index=True, blank=True, null=True) synonyms = models.ManyToManyField('self', symmetrical=False) to_show = 'name' @staticmethod def autocomplete_search_fields(): return ( "id__iexact", "name__icontains", ) def save(self, *args, **kwargs): super(StandardName, self).save(*args, **kwargs) if not (ColumnOrder.objects.filter(unificated_name=self).exists()): ColumnOrder.objects.create(unificated_name=self)
class APIToken(models.Model): """APItokens are used for authenticating to the api Endpoints may be connected to the token in which case the token also works as an authorization token. """ permission_choices = (('read', 'Read'), ('write', 'Write')) permission_help_text = "Read means that this token can be used for reading only. Write means that this token can be used to create new, update and delete objects as well as reading." token = VarcharField() expires = models.DateTimeField() created = models.DateTimeField(auto_now_add=True) client = models.ForeignKey(Account, db_column='client') scope = models.IntegerField(null=True, default=0) comment = models.TextField(null=True, blank=True) revoked = models.BooleanField(default=False) last_used = models.DateTimeField(null=True) endpoints = hstore.DictionaryField(null=True, blank=True) permission = VarcharField(choices=permission_choices, help_text=permission_help_text, default='read') objects = hstore.HStoreManager() def __str__(self): return self.token def is_expired(self): """Check is I am expired""" return self.expires < datetime.now() def get_absolute_url(self): """Special method that Django uses as default url for an object""" return reverse('useradmin-token_detail', args=[self.pk]) class Meta(object): db_table = 'apitoken'
class HstoreMixin(models.Model): """ Data field to be added to model to enable Hstore field. Actual hstore field hidden with underscore, property field serializes and deserializes data upon setting/getting. """ _data = hstore.DictionaryField( 'KeyValueStore', db_index=True, default={}, blank=True, null=True ) objects = hstore.HStoreManager() class Meta: abstract = True def clean(self): """ Ensure that all Hstore data is stored as valid JSON. NOTE: By default, this is not called automatically when you call save() method. """ if self._data: for key, value in self._data.items(): try: JsonDict.deserializeValue(value) except ValueError: msg = "The value of key \"%s\" does not appear to be valid JSON: %s. " % (key, value) msg += "Hstore values must be stored as JSON. Maybe you meant to use %s?" % JsonDict.serializeValue(value) raise ValidationError(msg) return super(HstoreMixin, self).clean() @property def data(self): """ Decode data from JSON """ return JsonDict(self._data, modelInstance=self) @data.setter def data(self, value): """ Encode data to JSON """ self._data = JsonDict.serializeDict(value) if value else {}
class FormSubmission(models.Model): form_id = models.CharField(max_length=256) uuid = models.CharField( max_length=36, validators=[ RegexValidator( regex=UUID_REGEX, message='Requires a 36 character UUID v4 formatted string', code='nomatch') ]) data = hstore.DictionaryField(help_text='Hstore of Ona form submission') submission_time = models.DateTimeField( help_text="Copied from the hstore data") objects = hstore.HStoreManager() @staticmethod def from_ona_form_data(submission): """ Create and return a new FormSubmission based on form data received from a mobile form submission """ uuid = submission._uuid obj = FormSubmission( form_id=submission.form_id, uuid=uuid, submission_time=submission._submission_time, data=submission.json, ) try: obj.clean_fields() except ValidationError: logger.exception( "FormSubmission with malformed uuid %s not imported" % uuid) else: obj.save()
class Place(models.Model): osm_type = models.CharField(max_length=1) osm_id = models.IntegerField(primary_key=True) class_field = models.TextField( db_column='class' ) # Field renamed because it was a Python reserved word. type = models.TextField() name = hstore.DictionaryField(blank=True) # This field type is a guess. admin_level = models.IntegerField(null=True, blank=True) housenumber = models.TextField(blank=True) street = models.TextField(blank=True) isin = models.TextField(blank=True) postcode = models.TextField(blank=True) country_code = models.CharField(max_length=2, blank=True) extratags = models.TextField(blank=True) # This field type is a guess. geometry = models.TextField() # This field type is a guess. objects = hstore.HStoreManager() class Meta: managed = False db_table = 'place' unique_together = ('osm_id', 'class_field')
class Bill(models.Model): date = models.DateField(verbose_name="日期") amount = models.FloatField(verbose_name="金额") bill_type = models.IntegerField(verbose_name="类型", default=BillType.Expense.code, choices=BillType.all()) remark = models.TextField(verbose_name="备注", blank=True) category = models.ForeignKey("Category", verbose_name="分类") data = hstore.DictionaryField(blank=True, verbose_name="数据") created = models.DateTimeField(verbose_name='创建时间', default=timezone.now) updated = models.DateTimeField(verbose_name='更新时间', auto_now=True) objects = hstore.HStoreManager() @property def bill_type_name(self): return BillType.from_code(self.bill_type).description def __str__(self): return "账单:{0},{1}{2}元".format(self.date, self.bill_type_name, self.amount) class Meta: verbose_name = "记账本" verbose_name_plural = verbose_name
class Account(models.Model): """ NAV's basic account model""" DEFAULT_ACCOUNT = 0 ADMIN_ACCOUNT = 1 # An overview of current preferences. # They should start with PREFERENCE_KEY PREFERENCE_KEY_LANGUAGE = 'language' # AlertProfiles PREFERENCE_KEY_STATUS = 'status-preferences' PREFERENCE_KEY_WIDGET_COLUMNS = 'widget_columns' PREFERENCE_KEY_REPORT_PAGE_SIZE = 'report_page_size' PREFERENCE_KEY_WIDGET_DISPLAY_DENSITY = 'widget_display_density' # FIXME get this from setting. MIN_PASSWD_LENGTH = 8 login = VarcharField(unique=True) name = VarcharField() password = VarcharField() ext_sync = VarcharField() preferences = hstore.DictionaryField() objects = hstore.HStoreManager() organizations = models.ManyToManyField(Organization, db_table='accountorg') class Meta(object): db_table = u'account' ordering = ('login', ) def __unicode__(self): return self.login def get_active_profile(self): """Returns the account's active alert profile""" try: return self.alertpreference.active_profile except (AlertPreference.DoesNotExist, AlertProfile.DoesNotExist): pass def get_groups(self): """Fetches and returns this users groups. Also stores groups in this object for later use. """ try: return self._cached_groups except AttributeError: self._cached_groups = self.accountgroup_set.values_list('id', flat=True) return self._cached_groups def get_privileges(self): """Fetches privileges for this users groups. Also stores privileges in this object for later use. """ try: return self._cached_privileges except AttributeError: self._cached_privileges = Privilege.objects.filter( group__in=self.get_groups()) return self._cached_privileges def get_tools(self): """Get the tool list for this account""" return [ tool for tool in self.accounttool_set.all().order_by('priority') if self.has_perm('web_access', tool.tool.uri) ] def has_perm(self, action, target): """Checks if user has permission to do action on target.""" groups = self.get_groups() privileges = self.get_privileges() if AccountGroup.ADMIN_GROUP in groups: return True elif privileges.count() == 0: return False elif action == 'web_access': for privilege in privileges: regexp = re.compile(privilege.target) if regexp.search(target): return True return False else: return privileges.filter(target=target).count() > 0 def is_system_account(self): """Is this system (undeleteable) account?""" return self.id < 1000 def is_default_account(self): """Is this the anonymous user account?""" return self.id == self.DEFAULT_ACCOUNT def is_admin_account(self): """Is this the admin account?""" return self.id == self.ADMIN_ACCOUNT def is_admin(self): """Has this user administrator rights?""" return self.has_perm(None, None) @sensitive_variables('password') def set_password(self, password): """Sets user password. Copied from nav.db.navprofiles""" if len(password.strip()): pw_hash = nav.pwhash.Hash(password=password) self.password = str(pw_hash) else: self.password = '' @sensitive_variables('password') def check_password(self, password): """ Return True if the submitted authentication tokens are valid for this Account. In simpler terms; when password authentication is used, this method compares the given password with the one stored for this account and returns true if they are equal. If the stored password is blank, we interpret this as: 'The user is not allowed to log in' In the future, this could be extended to accept other types of authentication tokens, such as personal certificates or whatever. Copied from nav.db.navprofiles """ # FIXME If password is old style NAV MD5, shouldn't we update the # password in the database to be new style password? if not self.locked: stored_hash = nav.pwhash.Hash() try: stored_hash.set_hash(self.password) except nav.pwhash.InvalidHashStringError: # Probably an old style NAV password hash, get out # of here and check it the old way pass else: return stored_hash.verify(password) # If the stored password looks like an old-style NAV MD5 # hash we compute the MD5 hash of the supplied password # for comparison. if self.password[:3] == 'md5': pw_hash = md5(password) return pw_hash.hexdigest() == self.password[3:] else: return password == self.password else: return False @property def locked(self): return not self.password or self.password.startswith('!') @locked.setter def locked(self, value): if not value and self.password.startswith('!'): self.password = self.password[1:] elif value and not self.password.startswith('!'): self.password = '******' + self.password
class BadDefaultsModel(models.Model): a = hstore.DictionaryField(default=None, default_key_type='normal')
class DefaultsModel(models.Model): a = hstore.DictionaryField(default={}, default_key_type='normal') b = hstore.DictionaryField(default=None, null=True, default_key_type='normal') c = hstore.DictionaryField(default={'x': '1'}, default_key_type='normal')
class DefaultsModel(models.Model): a = hstore.DictionaryField(default={}) b = hstore.DictionaryField(default=None, null=True) c = hstore.DictionaryField(default={'x': '1'})
class Location(geo_models.Model): name = geo_models.CharField(max_length=32) data = hstore.DictionaryField() point = geo_models.GeometryField() objects = hstore.HStoreGeoManager()
class Test(models.Model): """Lays out a load of meta stuff about a particular test. The meta field should be used like this: Say we have a test like EA GQA, where they have numbered categories which correspond to a range of values, but it is not clear what the actual value obtained is - in this case, the meta field stores all the category IDs and the value stored in the through relationship would be the category identifier. With a test like La Motte 5982 TesTab Phosphate kit, the meta would contain the available colorimetric categories (which correspond to an actual PPM value - but only certain colorimetrics are available, rather than a continuous scale). With a presence/absence test, the meta would contain presence and absence categories, perhaps with a note about degree of certainty. The value stored in the through relationship would be 'present' or 'absent' """ parameter = models.ForeignKey(Parameter) name = models.CharField(max_length=100) description = models.TextField(null=True, blank=True) vendor_or_authority = models.CharField( max_length=100, help_text="The name of the Manufacturer, Vendor, or Authority etc " "associated with this test.") unit = models.CharField(max_length=50) meta = hstore.DictionaryField( help_text="Describe all the potential values this test can result in.") test_type = models.CharField(max_length=20, choices=(('CATEGORY', 'Category'), ('VALUE', 'Value'), ('TEXT', 'Text'), ('PRESENCE', 'Present/Absent'))) def __unicode__(self): return u"{0} ({1})".format(self.name, self.vendor_or_authority) def get_value(self, value): """Return the correct value from meta given the TestValue value. Depends on the type of this test - if it is category it will do some lookup, otherwise it's pretty much just a passthrough. """ if self.test_type == 'CATEGORY': category = json.loads(self.meta[value]) result = [] if 'min' in category: result.append("from {0}".format(category['min'])) if 'max' in category: result.append("up to {0}".format(category['max'])) return " ".join(result) else: # maybe something more clever below... return value def get_stats(self): """Return some basics about this test, if possible.""" result = {} values = self.testvalue_set.values_list('value', flat=True) result['usage'] = "Used {0} times".format(len(values)) if self.test_type in ['CATEGORY', 'VALUE']: values = map(float, values) counter = Counter(values) result['mode'] = "{0}, {1} times".format( *counter.most_common(1)[0]) result['mean'] = "{0:0.2f}".format( sum(values) / float(len(values))) return result
class Order(BaseOrder): FEEDBACK_CHOICES = (('UP', 'Happy'), ('DOWN', 'Unhappy')) coffee = models.ForeignKey(CoffeeType) different = models.BooleanField(verbose_name='Different?', default=False) amount = models.DecimalField(verbose_name='Amount', max_digits=6, decimal_places=2, default=18) interval = models.PositiveIntegerField(verbose_name='Shipping Interval', default=14) recurrent = models.BooleanField(verbose_name='Recurrent?', default=False) # TODO: move existing feedback to review and remove it feedback = models.CharField(max_length=16, choices=FEEDBACK_CHOICES, null=True, blank=True) brew = models.ForeignKey(BrewMethod) package = models.CharField(verbose_name='Packaging method', max_length=16, choices=Preferences.PACKAGE_CHOICES, default=Preferences.GRINDED) details = hstore.DictionaryField(default={}, blank=True) objects = hstore.HStoreManager() resent = models.BooleanField(verbose_name='Resent Order?', default=False) custom_price = models.BooleanField(verbose_name='Custom Price?', default=False) def __unicode__(self): return '[{}] {} | {} | {} | {} | {}'.format( self.id, self.get_status_display(), timezone.localtime(self.date).strftime('%b, %d (%H:%M)'), timezone.localtime(self.shipping_date).strftime('%b, %d (%H:%M)'), self.customer, self.coffee, ) def save(self, *args, **kwargs): if (self.coffee.is_discovery_pack and 'discovery_coffees' not in self.details): self.update_discovery_coffees(commit=False) super(Order, self).save(*args, **kwargs) @property def is_editable(self): now = CTZ.normalize(timezone.now()) is_friday = now.isoweekday() == 5 shipping_date_is_monday = self.shipping_date.isoweekday() == 1 next_48h = now + timedelta(hours=48) next_96h = now + timedelta(hours=96) if (self.recurrent and not (is_friday and shipping_date_is_monday and next_96h > self.shipping_date) and (next_48h < self.shipping_date)): return True return False @property def is_paused(self): return self.status == self.PAUSED @property def is_first_order(self): """Check if this order is the first customer order.""" is_first = False try: is_first = self.id == self.customer.orders.earliest('id').id except Order.DoesNotExist: pass return is_first def hours_to_change(self): """Return hours left to make changes to this order.""" uneditable_at = self.shipping_date - timedelta(hours=48) delta = CTZ.normalize(uneditable_at) - CTZ.normalize(timezone.now()) delta_hrs = int(delta.total_seconds() / 3600) return 1 if delta_hrs == 0 else delta_hrs def get_next_shipping_date(self, after=None): now = after or CTZ.normalize(timezone.now()) possible_day = now + timedelta(days=self.interval) day = possible_day.isoweekday() today = possible_day.replace(hour=12, minute=0, second=0, microsecond=0) # noon = now.replace(hour=12, minute=0, second=0, microsecond=0) # morning = True if now < noon else False # Mon, Tue, Wed, Thu, Fri if day in range(1, 6): # return today if morning else tomorrow return today # Saturday elif day == 6: return today + timedelta(days=2) # Sunday elif day == 7: return today + timedelta(days=1) def get_after_next_shipping_date(self): return self.get_next_shipping_date(after=self.shipping_date) def get_discovery_coffee_ids(self): return json.loads(self.details['discovery_coffees']) def update_discovery_coffees(self, commit=True): self.details['discovery_coffees'] = [ c.id for c in (CoffeeType.objects.discovery_pack(self.customer)) ] if commit: self.save(update_fields=['details']) @cached_property def discovery_coffees(self): coffee_ids = self.get_discovery_coffee_ids() coffees = CoffeeType.objects.filter(id__in=coffee_ids) reviews = { review.coffee.id: review for review in self.reviews.filter(coffee_id__in=coffee_ids) } for coffee in coffees: coffee.review = reviews.get(coffee.id, {}) return coffees
class Job(CommonFieldsMixin): """Job post associated with project.""" related_name = 'jobs' related_query_name = 'job' created_by = models.ForeignKey(User, db_index=True, related_name='created_jobs', related_query_name='created_job', on_delete=models.CASCADE) group = models.ForeignKey(Group, null=True, blank=True, related_name=related_name, related_query_name=related_query_name) applicants = models.ManyToManyField(User, through='application.Application', related_name=related_name, related_query_name=related_query_name) role_position = models.CharField( null=True, blank=True, max_length=255, help_text= 'For eg. lead character, supporting character, background dancer etc.') ages = IntegerRangeField(null=True, blank=True, help_text='Age range required for this role.') required_gender = models.CharField(max_length=2, choices=choices.GENDER_CHOICES, default=choices.NOT_SPECIFIED) required_tokens = models.IntegerField( default=5, help_text='How much tokens user needs to have to apply to this job.') location = models.ForeignKey( City, null=True, blank=True, help_text="Location of user's project experience.") required_information_to_apply = hstore.DictionaryField(null=True, blank=True) reason_for_rejection = models.CharField( max_length=255, null=True, blank=True, help_text='Reason why the job was rejected/unapproved by stageroute.') submission_deadline = models.DateField( null=True, blank=True, help_text='Date for the job deadline.') status = models.CharField(max_length=2, choices=choices.JOB_STATE_CHOICES, default=choices.PENDING_APPROVAL) number_of_vacancies = models.IntegerField( default=1, help_text='How many positions are open for this job.') budgets = IntegerRangeField( null=True, blank=True, help_text='budget range amount to be spent on the job.') featured = models.BooleanField(default=False, help_text='Is job featured.') skin_type = models.CharField(max_length=50, null=True, blank=True, default=choices.DOES_NOT_MATTER, choices=choices.SKIN_TYPE_CHOICES, help_text='Preferred skin type.') hair_type = models.CharField(max_length=50, null=True, blank=True, default=choices.DOES_NOT_MATTER, choices=choices.HAIR_TYPE_CHOICES, help_text='Preferred hair type.') eye_color = models.CharField(max_length=50, default=choices.DOES_NOT_MATTER, null=True, blank=True, choices=choices.EYE_COLOR_CHOICES, help_text='Peferred eye color.') hair_color = models.CharField(max_length=50, default=choices.DOES_NOT_MATTER, null=True, blank=True, choices=choices.HAIR_COLOR_CHOICES, help_text='Peferred eye color.') hair_style = models.CharField(max_length=50, default=choices.DOES_NOT_MATTER, null=True, blank=True, choices=choices.HAIR_STYLE_CHOICES, help_text='Peferred eye color.') heights = FloatRangeField(null=True, blank=True, help_text='Range of height required.') body_type = models.CharField(max_length=50, null=True, blank=True, default=choices.DOES_NOT_MATTER, choices=choices.BODY_TYPES) language = models.CharField(max_length=50, null=True, blank=True, default=choices.DOES_NOT_MATTER, choices=choices.LANGUAGE_CHOICES, help_text='Preferred languages.') job_type = models.CharField(max_length=50, null=True, blank=True, choices=choices.JOB_TYPE_CHOICES, help_text='Type of job.') auditions_per_day = models.IntegerField( null=True, blank=True, help_text='Number of auditions to do per day for this job.') audition_range = DateRangeField(null=True, blank=True, help_text='Audition range') job_owner_email = models.EmailField( null=True, blank=True, help_text='Should be valid email, e.g. [email protected]', ) job_owner_phone = models.CharField(max_length=10, null=True, blank=True, db_index=True, help_text="User's phone number.") notes = models.CharField( max_length=255, null=True, blank=True, help_text="Useful for job posters. A quick note they can refere later." ) field_history = FieldHistoryTracker(['status']) related_query_name = 'jobs' images = GenericRelation(Image, related_query_name=related_query_name) videos = GenericRelation(Video, related_query_name=related_query_name) audios = GenericRelation(Audio, related_query_name=related_query_name) objects = hstore.HStoreManager() def __unicode__(self): """unicode.""" return self.title
class BadDefaultsModel(models.Model): a = hstore.DictionaryField(default=None)
class SchemaDataBag(HStoreModel): name = models.CharField(max_length=32) data = hstore.DictionaryField(schema=[ { 'name': 'number', 'class': 'IntegerField', 'kwargs': { 'default': 1 } }, { 'name': 'float', 'class': models.FloatField, 'kwargs': { 'default': 1.0 } }, { 'name': 'boolean', 'class': 'BooleanField', }, { 'name': 'boolean_true', 'class': 'BooleanField', 'kwargs': { 'verbose_name': 'boolean true', 'default': True } }, { 'name': 'char', 'class': 'CharField', 'kwargs': { 'default': 'test', 'blank': True, 'max_length': 10 } }, { 'name': 'text', 'class': 'TextField', 'kwargs': { 'blank': True } }, { 'name': 'choice', 'class': 'CharField', 'kwargs': { 'blank': True, 'max_length': 10, 'choices': (('choice1', 'choice1'), ('choice2', 'choice2')), 'default': 'choice1' } }, { 'name': 'choice2', 'class': 'CharField', 'kwargs': { 'blank': True, 'max_length': 10, 'choices': (('choice1', 'choice1'), ('choice2', 'choice2')), } }, { 'name': 'date', 'class': 'DateField', 'kwargs': { 'blank': True } }, { 'name': 'datetime', 'class': 'DateTimeField', 'kwargs': { 'blank': True } }, { 'name': 'decimal', 'class': 'DecimalField', 'kwargs': { 'blank': True, 'decimal_places': 2, 'max_digits': 4 } }, { 'name': 'email', 'class': 'EmailField', 'kwargs': { 'blank': True } }, { 'name': 'ip', 'class': 'GenericIPAddressField', 'kwargs': { 'blank': True, 'null': True } }, { 'name': 'url', 'class': models.URLField, 'kwargs': { 'blank': True } }, ])
class GearOrder(BaseOrder): gear = models.ForeignKey(CoffeeGear) # TODO: rename `price` to `amount` and move to parent class price = models.DecimalField(max_digits=6, decimal_places=2) details = hstore.DictionaryField(schema=[ { 'name': 'Colour', 'class': 'CharField', 'kwargs': { 'blank': True, 'max_length': 30 } }, { 'name': 'Quantity', 'class': 'IntegerField', 'kwargs': { 'default': 1 } }, { 'name': 'packaging', 'class': 'CharField', 'kwargs': { 'blank': True, 'max_length': 30 } }, { 'name': 'brew_method', 'class': 'CharField', 'kwargs': { 'blank': True, 'max_length': 30 } }, { 'name': 'staff_remarks', 'verbose_name': 'Remarks for Packing team', 'class': 'TextField', 'kwargs': { 'blank': True, 'max_length': 256, } }, { 'name': 'gift_note', 'verbose_name': 'Christmas gift note', 'class': 'TextField', 'kwargs': { 'blank': True, 'max_length': 600, } }, { 'name': 'Pre-Order', 'class': 'BooleanField', 'kwargs': { 'default': False } }, # { # 'name': 'shipped_to', # 'class': 'CharField', # 'kwargs': { # 'blank': True, # 'max_length': 1000 # } # }, ]) tracking_number = models.CharField(max_length=30, blank=True) objects = GearOrderManager() def __unicode__(self): return '[G{}] {} | {} | {} | {} | {}'.format( self.id, self.get_status_display(), timezone.localtime(self.date).strftime('%b, %d (%H:%M)'), timezone.localtime(self.shipping_date).strftime('%b, %d (%H:%M)'), self.customer, self.gear, ) @cached_property def is_editable(self): return False
class UniqueTogetherDataBag(HStoreModel): name = models.CharField(max_length=32) data = hstore.DictionaryField() class Meta: unique_together = ('name', 'data')
class DataBag(HStoreModel): name = models.CharField(max_length=32) data = hstore.DictionaryField()
class DataBag(HStoreModel): name = models.CharField(max_length=32) data = hstore.DictionaryField(json_keys=['json'], default_key_type='normal')
class Image(BaseCollectionItem): file = models.FileField( upload_to=upload_img_to, null=False, blank=False, storage=DoubleExtensionStorage(), verbose_name='File with the unthresholded map (.img, .nii, .nii.gz)') figure = models.CharField( help_text= "Which figure in the corresponding paper was this map displayed in?", verbose_name="Corresponding figure", max_length=200, null=True, blank=True) thumbnail = models.FileField( help_text="The orthogonal view thumbnail path of the nifti image", null=True, blank=True, upload_to=upload_img_to, verbose_name='Image orthogonal view thumbnail 2D bitmap', storage=DoubleExtensionStorage()) reduced_representation = models.FileField( help_text= ("Binary file with the vector of in brain values resampled to lower resolution" ), verbose_name="Reduced representation of the image", null=True, blank=True, upload_to=upload_img_to, storage=OverwriteStorage()) data = hstore.DictionaryField(blank=True, null=True) hstore_objects = hstore.HStoreManager() def get_absolute_url(self): return_args = [str(self.id)] url_name = 'image_details' if self.collection.private: return_args.insert(0, str(self.collection.private_token)) url_name = 'private_image_details' return reverse(url_name, args=return_args) def get_thumbnail_url(self): try: url = self.thumbnail.url except ValueError: url = os.path.abspath( os.path.join("/static", "images", "glass_brain_empty.jpg")) return url @classmethod def create(cls, my_file, my_file_name, my_name, my_desc, my_collection_pk, my_map_type): my_collection = Collection.objects.get(pk=my_collection_pk) # Copy the nifti file into the proper location image = cls(description=my_desc, name=my_name, collection=my_collection) f = open(my_file) niftiFile = File(f) image.file.save(my_file_name, niftiFile) # If a .img file was loaded then load the correspoding .hdr file as well _, ext = os.path.splitext(my_file_name) print ext if ext in ['.img']: f = open(my_file[:-3] + "hdr") hdrFile = File(f) image.hdr_file.save(my_file_name[:-3] + "hdr", hdrFile) image.map_type = my_map_type # create JSON file for neurosynth viewer if os.path.exists(image.file.path): nifti_gz_file = ".".join( image.file.path.split(".")[:-1]) + '.nii.gz' nii = nb.load(image.file.path) nb.save(nii, nifti_gz_file) f = open(nifti_gz_file) image.nifti_gz_file.save(nifti_gz_file.split(os.path.sep)[-1], File(f), save=False) image.save() return image # Celery task to generate glass brain image on new/update def save(self): file_changed = False collection_changed = False if self.pk is not None: old_pk = Image.objects.get(pk=self.pk) if old_pk.file != self.file: file_changed = True if old_pk.collection != self.collection: collection_changed = True do_update = True if file_changed else False new_image = True if self.pk is None else False super(Image, self).save() if (do_update or new_image ) and self.collection and self.collection.private == False: # Generate glass brain image generate_glassbrain_image.apply_async([self.pk]) if collection_changed: for field_name in self._meta.get_all_field_names(): field_instance = getattr(self, field_name) if field_instance and isinstance(field_instance, FieldFile): old_path = field_instance.path new_name = upload_img_to( self, field_instance.name.split("/")[-1]) new_name = field_instance.storage.get_available_name( new_name) new_path = field_instance.storage.path(new_name) if not os.path.exists(os.path.dirname(new_path)): os.mkdir(os.path.dirname(new_path)) shutil.copy(old_path, new_path) field_instance.name = new_name assert (old_path != new_path) os.remove(old_path) super(Image, self).save()
class JsonBag(HStoreModel): name = models.CharField(max_length=32) data = hstore.DictionaryField(normal_keys=['normal'])