class Options(EmbeddedDocument): access_key = fields.StringField() droplets = fields.ListField(fields.StringField()) ssh_pub_keys = fields.ListField(fields.DictField()) size = fields.StringField() region = fields.StringField() image = fields.StringField() state = fields.StringField() service_opts = fields.DictField(blank=True)
class Addon(Document): name = fields.StringField(unique_with=['type', 'version']) type = fields.StringField(choices=('cloud', 'service')) category = fields.StringField() author = fields.StringField() version = fields.StringField() depends = fields.ListField(fields.StringField(), blank=True) clouds = fields.ListField(fields.StringField(), blank=True) fields = fields.ListField(fields.DictField())
class DataCached(Document): """ DataCached object that has been cached by the system """ cached_documents_dict = fields.ListField(blank=False) cached_documents_objects = fields.ListField(blank=True) current_node = fields.StringField(blank=False) @staticmethod def get_all(): """ Get all DataCached objects. Returns: """ return DataCached.objects().all() @staticmethod def get_by_id(data_cached_id): """ Return the object with the given id. Args: data_cached_id: Returns: DataCached Object """ try: return DataCached.objects.get(pk=str(data_cached_id)) except mongoengine_errors.DoesNotExist as e: raise exceptions.DoesNotExist(str(e)) except Exception as ex: raise exceptions.ModelError(str(ex)) def save_object(self): """ Custom save. Returns: Saved Instance. """ try: return self.save() except mongoengine_errors.NotUniqueError as e: raise exceptions.NotUniqueError(str(e)) except Exception as ex: raise exceptions.ModelError(str(ex)) @staticmethod def delete_objects(): return DataCached.objects().delete()
class Template(dme_Document): """Represents an XML schema template that defines the structure of data for curation""" title = dme_fields.StringField() filename = dme_fields.StringField() content = dme_fields.StringField() templateVersion = dme_fields.StringField(blank=True) version = dme_fields.IntField(blank=True) hash = dme_fields.StringField() user = dme_fields.StringField(blank=True) dependencies = dme_fields.ListField(StringField(), blank=True) exporters = dme_fields.ListField(ReferenceField(Exporter, reverse_delete_rule=PULL), blank=True) XSLTFiles = dme_fields.ListField(ReferenceField(ExporterXslt, reverse_delete_rule=PULL), blank=True) ResultXsltList = dme_fields.ReferenceField(ResultXslt, reverse_delete_rule=NULLIFY, blank=True) ResultXsltDetailed = dme_fields.ReferenceField(ResultXslt, reverse_delete_rule=NULLIFY, blank=True)
class AbstractQuery(Document): """Abstract Query""" user_id = fields.StringField(blank=False) content = fields.StringField(blank=True) templates = fields.ListField( fields.ReferenceField(Template, blank=True), blank=True, default=[] ) data_sources = fields.ListField( fields.EmbeddedDocumentField(DataSource, blank=True), blank=True, default=[] ) meta = { "abstract": True, }
class User(Document): name = fields.StringField() username = fields.StringField(unique=True) email = fields.EmailField(unique=True) # these 2 fields are NOT TO BE FILLED ratings = fields.IntField(default=0) date_joined = fields.DateTimeField(default=timezone.now, editable=False) gears = fields.ListField(fields.ReferenceField('Gear'), default=[], blank=True) password = fields.StringField(min_length=8, max_length=128) USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['name', 'email', 'password'] def __str__(self): return self.username def get_username(self): return self.username def get_name(self): return self.name def get_ratings(self): return self.ratings def is_active(self): return True def check_password(self, raw_password): """ Checks the password if it matches the stored password """ return check_password(raw_password, self.password)
class TempChoiceListFile(Document): """ Model which associate a specific choice the list of files """ choice = fields.StringField() list_buckets = fields.ListField(fields.ReferenceField(TempBucketIdFiles, blank=True), blank=True) @staticmethod def get_all(): """Return all TempChoiceListFile. Returns: """ return TempChoiceListFile.objects().all() def delete_database(self): """ Delete function Delete each part of the choice and the associated files. """ for bucket in self.list_buckets: try: bucket_obj = TempBucketIdFiles.objects.get(id=bucket.id) bucket_obj.delete_database() except: pass self.delete()
class Post(Document): created_at = fields.DateTimeField( default=datetime.datetime.now, required=True, editable=False, ) title = fields.StringField(max_length=255, required=True) slug = fields.StringField(max_length=255, required=True, primary_key=True) comments = fields.ListField(fields.EmbeddedDocumentField('Comment')) def get_absolute_url(self): return reverse('post', kwargs={"slug": self.slug}) def __unicode__(self): return self.title @property def post_type(self): return self.__class__.__name__ meta = { 'indexes': ['-created_at', 'slug'], 'ordering': ['-created_at'], 'allow_inheritance': True }
class Group(document.Document): """Groups are a generic way of categorizing users to apply permissions, or some other label, to those users. A user can belong to any number of groups. A user in a group automatically has all the permissions granted to that group. For example, if the group Site editors has the permission can_edit_home_page, any user in that group will have that permission. Beyond permissions, groups are a convenient way to categorize users to apply some label, or extended functionality, to them. For example, you could create a group 'Special users', and you could write code that would do special things to those users -- such as giving them access to a members-only portion of your site, or sending them members-only e-mail messages. """ name = fields.StringField(max_length=80, unique=True, verbose_name=_('name')) permissions = fields.ListField( fields.ReferenceField(Permission, verbose_name=_('permissions'), required=False)) class Meta: verbose_name = _('group') verbose_name_plural = _('groups') def __unicode__(self): return self.name
class TemplateVersion(Document): """ Storage model for storing different versions of a template. :property name str: the template name being versioned :property version seq: the version for this template :property common ref: a reference to the common information record in the Template collection :property label str: the label to give to the root element :property spec ref: the TypeRenderSpec object to use to render the root element; if not set, this will be generated dynamically. :property tranforms ref: a reference to a record in Transforms that identifies the XSL stylesheets :property deleted bool: True if this version is currently deleted :property comment str: A brief (displayable) comment noting what is different about this version. """ name = fields.StringField(blank=False) version = fields.SequenceField(blank=False) common = fields.ReferenceField(TemplateCommon, blank=False) schema = fields.ReferenceField(SchemaVersion, blank=False) extschemas = fields.ListField(SchemaVersion, blank=True, default=[]) label = fields.StringField() spec = fields.ReferenceField(TypeRenderSpec, blank=True) # transforms = fields.ReferenceField(Transforms, blank=True) deleted = fields.BooleanField(blank=False, default=False) comment = fields.StringField(default="") @classmethod def get_all_by_name(cls, name, include_deleted=False): """ return a list of TemplateVersion records that have given name :param name str: the name of the template to match :param include_deleted bool: if False, return only records that have not been marked as deleted. """ vers = TemplateVersion.objects.filter(name=name) if not include_deleted: vers = vers.filter(deleted=False) return vers @classmethod def get_by_version(cls, name, version, include_deleted=False): """ return the TemplateVersion record with a given name and version. :param name str: the name of the schema to match :param version int: the version of the schema to select :param include_deleted bool: if False, return only records that have not been marked as deleted. """ vers = cls.get_all_by_name(name, include_deleted).filter(version=version) if len(vers) > 0: return vers[0] return None
class SchemaElement(Document): tag = fields.StringField() value = fields.StringField(default=None, blank=True) options = fields.DictField(blank=True) children = fields.ListField(fields.ReferenceField('SchemaElement'), blank=True)
class Bucket(Document): """Bucket class to store types by domain.""" label = fields.StringField(unique=True) color = fields.StringField(unique=True) types = fields.ListField(fields.ReferenceField(TypeVersionManager), blank=True) @staticmethod def get_by_id(bucket_id): """Return a bucket given its id. Args: bucket_id: Returns: """ try: return Bucket.objects.get(pk=str(bucket_id)) except mongoengine_errors.DoesNotExist as e: raise exceptions.DoesNotExist(str(e)) except Exception as ex: raise exceptions.ModelError(str(ex)) @staticmethod def get_all(): """Return all buckets. Returns: """ return Bucket.objects().all() @staticmethod def get_colors(): """Return all colors. Returns: """ return Bucket.objects.values_list("color") def save_object(self): """Custom save Returns: """ try: return self.save() except mongoengine_errors.NotUniqueError as e: raise exceptions.NotUniqueError(str(e)) except Exception as ex: raise exceptions.ModelError(str(ex))
class Event(Document): title = fields.StringField(max_length=255) description = fields.StringField(max_length=255) location = fields.StringField(max_length=255) landmark = fields.StringField(max_length=255) city = fields.StringField(max_length=255) coordinates = fields.ListField(fields.FloatField()) start_timestamp = fields.DateTimeField() end_timestamp = fields.DateTimeField() banner = fields.StringField() #banner = fields.ImageField(upload_to='banners', default="images/None/no-img.jpeg") #banner = fields.ImageField(upload_to=fs, default="images/None/no-img.jpeg") tags = fields.ListField(fields.StringField()) recurring = fields.BooleanField(default=False) open_event = fields.BooleanField(default=True) full_day_event = fields.BooleanField(default=False) created_by = fields.IntField() user_agent = fields.StringField(blank=True) timestamp = fields.DateTimeField(default=datetime.datetime.now) updated_at = fields.DateTimeField(default=datetime.datetime.now) slug = fields.StringField(blank=True) ip_address = fields.StringField(blank=True) channel = fields.ObjectIdField() deleted = fields.BooleanField(default=False) deleted_at = fields.DateTimeField(blank=True) meta = {'collection': 'events'} def __str__(self): return self.title @classmethod def pre_save(cls, sender, document, **kwargs): document.title = document.title.capitalize() document.description = document.description.capitalize() document.location = document.location.title() document.landmark = document.landmark.title() document.city = document.city.title() if not document.slug: document.slug = slugify(document.title)
class TransformResult(Document): """ Represents a result after transformation source_document_name: It will be the source document name like "myFile.xml" transform_result_content: List of result. One result expected for simple conversion like XML, Json but zero or N result for blob export """ source_document_name = fields.StringField(default="") transform_result_content = fields.ListField(TransformResultContent)
class DataItem(Document): """ Data Item object """ # When data is deleted, all relative data item is deleted as well data = fields.ReferenceField(Data, blank=False, reverse_delete_rule=CASCADE) template = fields.ReferenceField(Template, blank=False) list_content = fields.ListField(fields.EmbeddedDocumentField(Item), default=[], blank=False) last_modification_date = fields.DateTimeField(blank=True, default=None) @staticmethod def get_by_data(data): """ Return a Data Item with the data given. Args: data: Returns: """ try: return DataItem.objects(data=data).get() except mongoengine_errors.DoesNotExist as e: raise exceptions.DoesNotExist(e.message) except Exception as ex: raise exceptions.ModelError(ex.message) @staticmethod def delete_from_data(data): """ Delete data items relative to the given data Args: data: Returns: """ DataItem.objects(data=data).delete() @staticmethod def execute_query_distinct_by_data(query): """Execute a query on the DataItem collection distinct by data. Args: query: Returns: """ return DataItem.objects(__raw__=query).distinct("data")
class Book(Document): id = fields.StringField(primary_key=True, default=ObjectId) name = fields.StringField(max_length=300) slug = fields.StringField() pages = fields.IntField() authors = fields.ListField(fields.ReferenceField(Author)) pubdate = fields.DateTimeField() _meta = {"ordering": ["-pubdate"]} def __unicode__(self): return self.name or ""
class OaiProviderSet(OaiSet): """Represents a set for Oai-Pmh Provider""" templates_manager = fields.ListField(fields.ReferenceField( TemplateVersionManager, reverse_delete_rule=PULL), unique_with='set_spec') description = fields.StringField(blank=True) @staticmethod def get_all(order_by_field=None): """ Return all OaiProviderSet. Args: order_by_field: Order by field. Returns: List of OaiProviderSet. """ return OaiProviderSet.objects().order_by(order_by_field) @staticmethod def get_all_by_templates_manager(templates_manager): """ Get all OaiProviderSet used by a list of templates_manager Args: templates_manager: List of templates manager Returns: List of OaiProviderSet. """ return OaiProviderSet.objects( templates_manager__in=templates_manager).all() @staticmethod def get_by_set_spec(set_spec): """ Get an OaiProviderSet by its set_spec. Args: set_spec: OaiProviderSet set_spec. Returns: The OaiProviderSet instance. Raises: DoesNotExist: The set doesn't exist ModelError: Internal error during the process """ try: return OaiProviderSet.objects().get(set_spec=set_spec) except mongoengine_errors.DoesNotExist as e: raise exceptions.DoesNotExist(e.message) except Exception as e: raise exceptions.ModelError(e.message)
class Profile(Document): #user = fields.ReferenceField('User') user_id = fields.IntField() full_name = fields.StringField(max_length=191, blank=True) location = fields.DictField({}, blank=True) settings = fields.DictField({}, blank=True) has_at_least_one_social_account = fields.BooleanField(default=False) social_accounts = fields.ListField(fields.DictField({}, blank=True), blank=True) associated_platforms = fields.ListField(fields.DictField(), blank=True) channels = fields.ListField(fields.DictField(blank=True), blank=True) authorized_devices = fields.ListField(fields.DictField(blank=True), blank=True) birth_date = fields.DateTimeField(blank=True) roles = fields.ListField(fields.DictField({}, blank=True), blank=True) permissions = fields.ListField(fields.DictField({}, blank=True), blank=True) signed_up_with = fields.StringField(defalut="email") signed_up_ip_address = fields.StringField(blank=True) singed_up_user_agent = fields.StringField(blank=True) logged_in_ip_address = fields.StringField(blank=True) logged_in_user_agent = fields.StringField(blank=True) meta = {"collection": "auth_profile"} def __str__(self): return self.mobile_number def check_otp(self, otp): return check_password(otp, self.otp)
class ElasticsearchTemplate(Document): """ElasticsearchTemplate object""" template = fields.ReferenceField(Template, blank=False, reverse_delete_rule=CASCADE, unique=True) title_path = fields.StringField(default=None) description_paths = fields.ListField(blank=False, validation=validate_xpath_list, default=[]) @staticmethod def get_by_id(es_template_id): """Returns the object with a given id Args: es_template_id: Returns: ElasticsearchTemplate (obj): ElasticsearchTemplate """ try: return ElasticsearchTemplate.objects.get(pk=es_template_id) except mongoengine_errors.DoesNotExist as e: raise exceptions.DoesNotExist(str(e)) except Exception as e: raise exceptions.ModelError(str(e)) @staticmethod def get_by_template(template): """Returns the object with a given template Args: template: Returns: ElasticsearchTemplate (obj): ElasticsearchTemplate """ try: return ElasticsearchTemplate.objects.get(template=template) except mongoengine_errors.DoesNotExist as e: raise exceptions.DoesNotExist(str(e)) except Exception as e: raise exceptions.ModelError(str(e)) @staticmethod def get_all(): """Returns all objects""" return ElasticsearchTemplate.objects.all()
class Tmall(DynamicDocument): title = fields.StringField() store_id = fields.StringField() url = fields.URLField() price = fields.FloatField() sale_num = fields.IntField() image_urls = fields.ListField() scrapy_mongodb = fields.DictField(db_field='scrapy-mongodb') def __str__(self): return self.title @property def cover(self): return self.image_urls[0]
class DataStructureElement(Document): """Represents data structure object""" tag = fields.StringField() value = fields.StringField(blank=True) options = fields.DictField(default={}, blank=True) children = fields.ListField(fields.ReferenceField('self'), blank=True) @staticmethod def get_all(): """ Returns: """ return DataStructureElement.objects.all() @staticmethod def get_all_by_child_id(child_id): """ Get Data structure element object which contains the given child id in its children Args: child_id: Returns: """ try: return DataStructureElement.objects(children=ObjectId(child_id)).all() except Exception as ex: raise exceptions.ModelError(ex.message) @staticmethod def get_by_id(data_structure_element_id): """ Returns the object with the given id Args: data_structure_element_id: Returns: DataStructureElement (obj): DataStructureElement object with the given id """ try: return DataStructureElement.objects.get(pk=str(data_structure_element_id)) except mongoengine_errors.DoesNotExist as e: raise exceptions.DoesNotExist(e.message) except Exception as ex: raise exceptions.ModelError(ex.message)
class DynQuery(Document): """ Query object created by the administrator. """ # Query name name = fields.StringField(blank=False, unique=True) # Limit the query to number_records records is_limited = fields.BooleanField(blank=False, default=False) # Records number to limit the query number_records = fields.IntField(blank=True) # Group query group = fields.StringField(blank=False) # Schema associated to the query # FIXME: replace by a reference field schema = fields.StringField(blank=False) # List of step links to the query steps = fields.ListField( fields.ReferenceField(DynQueryStep, blank=False, reverse_delete_rule=CASCADE)) @staticmethod def get_by_id(dyn_query_id): """Return a DynQuery given its id. Args: dyn_query_id: Returns: """ try: return DynQuery.objects.get(pk=str(dyn_query_id)) except mongoengine_errors.DoesNotExist as e: raise exceptions.DoesNotExist(str(e)) except Exception as ex: raise exceptions.ModelError(str(ex)) @staticmethod def get_all(): """Return all DynQueries. Returns: """ return DynQuery.objects().all()
class TempBucketIdFiles(Document): """ Part of the input file """ list_files = fields.ListField(blank=True) @staticmethod def get_all(): """Return all TempBucketIdFiles. Returns: """ return TempBucketIdFiles.objects().all() def delete_database(self): """ Delete function """ self.delete()
class System(EmbeddedDocument): companyName = fields.StringField(blank=True) model = fields.StringField() fullModel = fields.StringField() osVersion = fields.StringField() patches = fields.ListField(fields.StringField(), blank=True) """ "patches" : [ "P01", "P02", "P04" ], """ sp = fields.DictField(blank=True) """ "sp" : { "spId" : "8094306", "spModel" : "ProLiant DL120 Gen9", "spVersion" : "5.0.0.0-22913 (5.0 GA)" }, """ productSKU = fields.StringField(blank=True, null=True) productFamily = fields.StringField(blank=True, null=True) recommended = fields.DictField(blank=True) """
class GlobalTypeAnnots(Document): """ Storage model for annotations on a global element. The purpose of this model separate from GlobalType is so that these annotations can be shared across the different versions of the type (from the different versions of the schema); in other words, when a new version of a schema is loaded, you don't loose all your annotations. :property name str: the local name for the element :property namespace str: the namespace URI of the schema within which the element is defined :property schemaname str: the unique name given to the schema document where the type is defined :property tag list: a list of strings representing subject tags :property hide boolean: True if this element should be normally hidden when offering root elements for templates. """ name = fields.StringField(unique_with=["namespace", "schemaname"]) namespace = fields.StringField() schemaname = fields.StringField() tag = fields.ListField(fields.StringField(), default=[], blank=True) hide = fields.BooleanField(default=False)
class OaiRequestPage(Document): """Informations about a request sent by a harvester needed a paginated response. """ resumption_token = fields.StringField(blank=False, unique=True) template_id_list = fields.ListField(blank=False) metadata_format = fields.StringField(blank=False) oai_set = fields.StringField(blank=True, default=None) from_date = fields.DateTimeField(blank=True, default=None) until_date = fields.DateTimeField(blank=True, default=None) expiration_date = fields.DateTimeField(blank=False, default=None) page_number = fields.IntField(blank=False) @staticmethod def get_by_resumption_token(resumption_token): try: return OaiRequestPage.objects.get( resumption_token=resumption_token) except mongoengine_errors.DoesNotExist as e: raise exceptions.DoesNotExist(str(e)) except Exception as ex: raise exceptions.ModelError(str(ex))
class Post(Document): created_at = fields.DateTimeField(default=datetime.datetime.now, editable=False) title = fields.StringField(max_length=255) slug = fields.StringField(max_length=255, primary_key=True) comments = fields.ListField(fields.EmbeddedDocumentField("Comment"), default=[], blank=True) def get_absolute_url(self): return reverse("post", kwargs={"slug": self.slug}) def __unicode__(self): return self.title @property def post_type(self): return self.__class__.__name__ meta = { "indexes": ["-created_at", "slug"], "ordering": ["-created_at"], "allow_inheritance": True, }
class Bucket(dme_Document): """Represents a bucket to store types by domain""" label = dme_fields.StringField(unique=True) color = dme_fields.StringField(unique=True) types = dme_fields.ListField(blank=True)
class User(document.Document): """A User document that aims to mirror most of the API specified by Django at http://docs.djangoproject.com/en/dev/topics/auth/#users """ username = fields.StringField( max_length=30, required=True, verbose_name=_('username'), help_text= _("Required. 30 characters or fewer. Letters, numbers and @/./+/-/_ characters" )) first_name = fields.StringField(max_length=30, verbose_name=_('first name')) last_name = fields.StringField(max_length=30, verbose_name=_('last name')) email = fields.EmailField(verbose_name=_('e-mail address')) password = fields.StringField( max_length=128, verbose_name=_('password'), help_text= _("Use '[algo]$[iterations]$[salt]$[hexdigest]' or use the <a href=\"password/\">change password form</a>." )) is_staff = fields.BooleanField( default=False, verbose_name=_('staff status'), help_text=_( "Designates whether the user can log into this admin site.")) is_active = fields.BooleanField( default=True, verbose_name=_('active'), help_text= _("Designates whether this user should be treated as active. Unselect this instead of deleting accounts." )) is_superuser = fields.BooleanField( default=False, verbose_name=_('superuser status'), help_text= _("Designates that this user has all permissions without explicitly assigning them." )) last_login = fields.DateTimeField(default=timezone.now, verbose_name=_('last login')) date_joined = fields.DateTimeField(default=timezone.now, verbose_name=_('date joined')) user_permissions = fields.ListField( fields.ReferenceField(Permission), verbose_name=_('user permissions'), help_text=_('Permissions for the user.')) USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email'] meta = { 'allow_inheritance': True, 'indexes': [{ 'fields': ['username'], 'unique': True, 'sparse': True }] } def __unicode__(self): return self.username def get_full_name(self): """Returns the users first and last names, separated by a space. """ full_name = u'%s %s' % (self.first_name or '', self.last_name or '') return full_name.strip() def is_anonymous(self): return False def is_authenticated(self): return True def set_password(self, raw_password): """Sets the user's password - always use this rather than directly assigning to :attr:`~mongoengine.django.auth.User.password` as the password is hashed before storage. """ self.password = make_password(raw_password) self.save() return self def check_password(self, raw_password): """Checks the user's password against a provided password - always use this rather than directly comparing to :attr:`~mongoengine.django.auth.User.password` as the password is hashed before storage. """ return check_password(raw_password, self.password) @classmethod def create_user(cls, username, password, email=None): """Create (and save) a new user with the given username, password and email address. """ now = timezone.now() # Normalize the address by lowercasing the domain part of the email # address. if email is not None: try: email_name, domain_part = email.strip().split('@', 1) except ValueError: pass else: email = '@'.join([email_name, domain_part.lower()]) user = cls(username=username, email=email, date_joined=now) user.set_password(password) user.save() return user def get_group_permissions(self, obj=None): """ Returns a list of permission strings that this user has through his/her groups. This method queries all available auth backends. If an object is passed in, only permissions matching this object are returned. """ permissions = set() for backend in auth.get_backends(): if hasattr(backend, "get_group_permissions"): permissions.update(backend.get_group_permissions(self, obj)) return permissions def get_all_permissions(self, obj=None): return _user_get_all_permissions(self, obj) def has_perm(self, perm, obj=None): """ Returns True if the user has the specified permission. This method queries all available auth backends, but returns immediately if any backend returns True. Thus, a user who has permission from a single auth backend is assumed to have permission in general. If an object is provided, permissions for this specific object are checked. """ # Active superusers have all permissions. if self.is_active and self.is_superuser: return True # Otherwise we need to check the backends. return _user_has_perm(self, perm, obj) def has_module_perms(self, app_label): """ Returns True if the user has any permissions in the given app label. Uses pretty much the same logic as has_perm, above. """ # Active superusers have all permissions. if self.is_active and self.is_superuser: return True return _user_has_module_perms(self, app_label) def email_user(self, subject, message, from_email=None): "Sends an e-mail to this User." from django.core.mail import send_mail send_mail(subject, message, from_email, [self.email]) def get_profile(self): """ Returns site-specific profile for this user. Raises SiteProfileNotAvailable if this site does not allow profiles. """ if not hasattr(self, '_profile_cache'): from django.conf import settings if not getattr(settings, 'AUTH_PROFILE_MODULE', False): raise SiteProfileNotAvailable('You need to set AUTH_PROFILE_MO' 'DULE in your project settings') try: app_label, model_name = settings.AUTH_PROFILE_MODULE.split('.') except ValueError: raise SiteProfileNotAvailable( 'app_label and model_name should' ' be separated by a dot in the AUTH_PROFILE_MODULE set' 'ting') try: model = models.get_model(app_label, model_name) if model is None: raise SiteProfileNotAvailable( 'Unable to load the profile ' 'model, check AUTH_PROFILE_MODULE in your project sett' 'ings') self._profile_cache = model._default_manager.using( self._state.db).get(user__id__exact=self.id) self._profile_cache.user = self except (ImportError, ImproperlyConfigured): raise SiteProfileNotAvailable return self._profile_cache
class Leaf(Document): """Leaf object that represent a final node from the navigation tree""" current_node_id = fields.StringField(blank=False) # list of id of the documents under the current leaf docs_list = fields.ListField(blank=False) @staticmethod def get_all(): """Get all Leaves objects. Returns: """ return Leaf.objects().all() @staticmethod def get_by_id(leaf_id): """Return the object with the given id. Args: leaf_id: Returns: Leaf Object """ try: return Leaf.objects.get(pk=str(leaf_id)) except mongoengine_errors.DoesNotExist as e: raise exceptions.DoesNotExist(str(e)) except Exception as ex: raise exceptions.ModelError(str(ex)) @staticmethod def get_by_current_node_id(current_node_id): """Return the object with the given id. Args: current_node_id: Returns: Leaf Objects """ try: return Leaf.objects.get(current_node_id=str(current_node_id)) except mongoengine_errors.DoesNotExist as e: raise exceptions.DoesNotExist(str(e)) except Exception as ex: raise exceptions.ModelError(str(ex)) def save_object(self): """Custom save. Returns: Saved Instance. """ try: return self.save() except mongoengine_errors.NotUniqueError as e: raise exceptions.NotUniqueError(str(e)) except Exception as ex: raise exceptions.ModelError(str(ex)) @staticmethod def delete_objects(): """Custom delete all Leaf objects. Returns: Delete all Instances. """ return Leaf.objects().delete()