示例#1
0
文件: models.py 项目: alanbuxey/djnro
class Realm(models.Model):
    '''
    Realm
    '''

    country = models.CharField(max_length=5, choices=get_choices_from_settings('REALM_COUNTRIES'))
    stype = models.PositiveIntegerField(default=0, editable=False)
    # TODO: multiple names can be specified [...] name in English is required
    org_name = fields.GenericRelation(Name_i18n)
    address_street = models.CharField(max_length=32)
    address_city = models.CharField(max_length=24)
    contact = models.ManyToManyField(Contact)
    url = fields.GenericRelation(URL_i18n)
    ts = models.DateTimeField(auto_now=True)

    class Meta:
        verbose_name = "Realm"
        verbose_name_plural = "Realms"

    def __str__(self):
        return _('Country: %(country)s, NRO: %(orgname)s') % {
            # but name is many-to-many from institution
            'orgname': ', '.join([i.name for i in self.org_name.all()]),
            'country': self.country,
        }

    get_name = Name_i18n.get_name_factory('org_name')
示例#2
0
class Institution(models.Model):
    '''
    Institution
    '''

    realmid = models.ForeignKey("Realm")
    instid = models.UUIDField(default=uuid.uuid4, unique=True, editable=False)
    org_name = fields.GenericRelation(Name_i18n)
    inst_name = fields.GenericRelation(Name_i18n)
    ertype = models.PositiveIntegerField(choices=ERTYPES, db_column='type')
    stage = models.PositiveIntegerField(
        choices=PRODUCTION_STATES,
        default=PRODUCTION_STATES.ACTIVE
    )

    def __str__(self):
        return "%s" % ', '.join([i.name for i in self.org_name.all()])

    get_name = Name_i18n.get_name_factory('org_name')

    def get_active_cat_enrl(self, cat_instance='production'):
        urls = []
        active_cat_enrl = self.catenrollment_set.filter(url='ACTIVE', cat_instance=cat_instance)
        for catenrl in active_cat_enrl:
            if catenrl.cat_configuration_url:
                urls.append(catenrl.cat_configuration_url)
        return urls

    def get_active_cat_ids(self, cat_instance='production'):
        ids = []
        active_cat_enrl = self.catenrollment_set.filter(url='ACTIVE', cat_instance=cat_instance)
        for catenrl in active_cat_enrl:
            ids.append(catenrl.cat_inst_id)
        return ids
示例#3
0
class SocialModel(models.Model):
    tags = fields.GenericRelation(TaggedItem)
    ratings = fields.GenericRelation(Rating)
    fans = fields.GenericRelation(Favorite)

    class Meta:
        abstract = True
示例#4
0
class Message(models.Model):
    association = models.ForeignKey(Association)
    objet = models.CharField(max_length=300)
    contenu = models.TextField()
    date = models.DateTimeField(default=datetime.now(), blank=True)
    expediteur = models.ForeignKey(
        UserProfile)  #L'élève qui a rédigé le message

    lu = models.ManyToManyField(UserProfile,
                                related_name='message_lu',
                                blank=True)  #Les élèves qui ont lu le message
    important = models.ManyToManyField(
        UserProfile, related_name='message_important',
        blank=True)  #Les élèves qui ont classé le message comme important

    commentaires = fields.GenericRelation(Comment, object_id_field="object_pk")
    notification = fields.GenericRelation(Notification)

    class Meta:
        ordering = ['-date']

    def get_absolute_url(self):
        return self.association.get_absolute_url() + 'messages/'

    def __str__(self):
        return self.objet

    @property
    def est_recent(self):
        return (self.date.date() == date.today())

    def envoyer_message_notification(self):
        message = self.association.nom + ' a publie un nouveau message'
        notification = Notification(content_object=self, description=message)
        notification.save()
        notification.envoyer_multiple(self.association.suivi_par.all())

    def envoyer_commentaire_notification(self, comment_pk, username):
        eleve = UserProfile.objects.get(user__username=username)
        message = eleve.first_name + ' ' + eleve.last_name + ' a commente un message de ' + self.association.nom
        commentaire = Comment.objects.get(pk=comment_pk)
        notification = Notification(content_object=commentaire,
                                    description=message)
        notification.save()
        notification.envoyer_multiple(self.association.suivi_par.all())

    def save(self, *args, **kwargs):
        creation = self.pk is None  #Creation de l'objet
        super(Message, self).save(*args, **kwargs)
        if creation:
            self.envoyer_message_notification()

    def html_to_text(self):
        s = HTMLTextExtractor()
        s.feed(self.contenu)
        return s.get_text()

    @staticmethod
    def accessibles_par(eleve):
        return Message.objects.filter(date__gte=eleve.date_entree_aux_mines())
示例#5
0
class MaintainerGroup(Model):
    """
    This model holds the information of the maintainer group like contact
    information,address,etc.
    """

    name = models.CharField(max_length=127, )
    homepage = models.URLField(blank=True, )
    acronym = models.CharField(
        max_length=63,
        blank=True,
    )

    description = models.TextField()

    medium_slug = models.CharField(
        max_length=63,
        blank=True,
    )

    contact_information = contenttypes_fields.GenericRelation(
        to='formula_one.ContactInformation',
        related_query_name='maintainer_group',
        content_type_field='entity_content_type',
        object_id_field='entity_object_id',
    )
    social_information = contenttypes_fields.GenericRelation(
        to='formula_one.SocialInformation',
        related_query_name='maintainer_group',
        content_type_field='entity_content_type',
        object_id_field='entity_object_id',
    )
    location_information = contenttypes_fields.GenericRelation(
        to='formula_one.LocationInformation',
        related_query_name='maintainer_group',
        content_type_field='entity_content_type',
        object_id_field='entity_object_id',
    )

    def save(self, *args, **kwargs):
        """
        Save the new object on the existing MaintainerGroup object
        """

        self.pk = 1
        self.datetime_created = datetime.datetime.now()
        self.name = settings.MAINTAINERS.text.name
        self.homepage = settings.MAINTAINERS.text.home_page or ''
        self.acronym = settings.MAINTAINERS.text.acronym or ''

        super().save(*args, **kwargs)

    def __str__(self):
        """
        Return the string representation of the object
        :return: the string representation of the object
        """

        return self.name
class AbstractPromotion(models.Model):
    """
    Abstract base promotion that defines the interface
    that subclasses must implement.
    """
    _type = 'Promotion'
    keywords = fields.GenericRelation(KeywordPromotion,
                                      verbose_name=_('Keywords'))
    pages = fields.GenericRelation(PagePromotion, verbose_name=_('Pages'))

    site = models.ForeignKey('sites.Site',
                             on_delete=models.CASCADE,
                             null=False,
                             blank=False,
                             default=1,
                             verbose_name=_('Site'))

    class Meta:
        abstract = True
        app_label = 'oscar_promotions'
        verbose_name = _("Promotion")
        verbose_name_plural = _("Promotions")

    @property
    def type(self):
        return _(self._type)

    @classmethod
    def classname(cls):
        return cls.__name__.lower()

    @property
    def code(self):
        return self.__class__.__name__.lower()

    def template_name(self):
        """
        Returns the template to use to render this promotion.
        """
        return 'oscar_promotions/%s.html' % self.code

    def template_context(self, request):
        return {}

    @property
    def content_type(self):
        return ContentType.objects.get_for_model(self)

    @property
    def num_times_used(self):
        ctype = self.content_type
        page_count = PagePromotion.objects.filter(content_type=ctype,
                                                  object_id=self.id).count()
        keyword_count \
            = KeywordPromotion.objects.filter(content_type=ctype,
                                              object_id=self.id).count()
        return page_count + keyword_count
示例#7
0
class ServiceLoc(models.Model):
    '''
    Service Location of an SP/IdPSP Institution
    '''

    ENCTYPES = (
        ('WPA/TKIP', 'WPA-TKIP'),
        ('WPA/AES', 'WPA-AES'),
        ('WPA2/TKIP', 'WPA2-TKIP'),
        ('WPA2/AES', 'WPA2-AES'),
    )

    # accept if institutionid.ertype: 2 (sp) or 3 (idpsp)
    institutionid = models.ForeignKey("Institution", verbose_name="Institution")
    longitude = models.DecimalField(max_digits=12, decimal_places=8)
    latitude = models.DecimalField(max_digits=12, decimal_places=8)
    # TODO: multiple names can be specified [...] name in English is required
    loc_name = fields.GenericRelation(Name_i18n)
    address_street = models.CharField(max_length=96)
    address_city = models.CharField(max_length=64)
    contact = models.ManyToManyField(Contact, blank=True)
    SSID = models.CharField(max_length=16)
    enc_level = MultiSelectField(max_length=64, choices=ENCTYPES, blank=True, null=True)
    port_restrict = models.BooleanField()
    transp_proxy = models.BooleanField()
    IPv6 = models.BooleanField()
    NAT = models.BooleanField()
    AP_no = models.PositiveIntegerField()
    wired = models.BooleanField()
    # only urltype = 'info' should be accepted here
    url = fields.GenericRelation(URL_i18n, blank=True, null=True)
    ts = models.DateTimeField(auto_now=True)

    class Meta:
        verbose_name = "Service Location"
        verbose_name_plural = "Service Locations"

    def __unicode__(self):
        return _('Institution: %(inst)s, Service Location: %(locname)s') % {
            # but name is many-to-many from institution
            'inst': self.institutionid,
            # but locname is many-to-many
            'locname': self.get_name(),
        }

    def get_name(self, lang=None):
        name = ', '.join([i.name for i in self.loc_name.all()])
        if not lang:
            return name
        else:
            try:
                name = self.loc_name.get(lang=lang)
                return name
            except Exception:
                return name
    get_name.short_description = 'Location Name'
示例#8
0
class AbstractPromotion(models.Model):
    """
    Abstract base promotion that defines the interface
    that subclasses must implement.
    定义子类必须实现的接口的抽象基础升级。
    """
    _type = 'Promotion'
    keywords = fields.GenericRelation(KeywordPromotion,
                                      verbose_name=_('Keywords'))
    pages = fields.GenericRelation(PagePromotion, verbose_name=_('Pages'))

    class Meta:
        abstract = True
        app_label = 'promotions'
        verbose_name = _("Promotion")
        verbose_name_plural = _("Promotions")

    @property
    def type(self):
        return _(self._type)

    @classmethod
    def classname(cls):
        return cls.__name__.lower()

    @property
    def code(self):
        return self.__class__.__name__.lower()

    def template_name(self):
        """
        Returns the template to use to render this promotion.
        返回用于呈现此促销的模板。
        """
        return 'promotions/%s.html' % self.code

    def template_context(self, request):
        return {}

    @property
    def content_type(self):
        return ContentType.objects.get_for_model(self)

    @property
    def num_times_used(self):
        ctype = self.content_type
        page_count = PagePromotion.objects.filter(content_type=ctype,
                                                  object_id=self.id).count()
        keyword_count \
            = KeywordPromotion.objects.filter(content_type=ctype,
                                              object_id=self.id).count()
        return page_count + keyword_count
示例#9
0
class InstitutionDetails(models.Model):
    '''
    Institution Details
    '''
    institution = models.OneToOneField(Institution)
    # TODO: multiple addresses can be specified [...] address in English is required
    address = fields.GenericRelation(Address_i18n)
    coordinates = models.ForeignKey(
        Coordinates,
        on_delete=models.SET_NULL,
        blank=True,
        null=True
    )
    contact = models.ManyToManyField(Contact)
    url = fields.GenericRelation(URL_i18n)
    # accept if ertype: 2 (sp) or 3 (idpsp) (Applies to the following field)
    oper_name = models.CharField(
        max_length=252,
        null=True,
        blank=True,
        help_text=_('The primary, registered domain name for your institution, eg. example.com.<br>This is used to derive the Operator-Name attribute according to RFC5580, par.4.1, using the REALM namespace.')
    )
    venue_info = models.CharField(
        max_length=7,
        blank=True,
        validators=[validate_venue_info],
        db_column='inst_type',
        help_text=_VENUE_INFO_HELP_TEXT
    )
    # accept if ertype: 1 (idp) or 3 (idpsp) (Applies to the following field)
    number_user = models.PositiveIntegerField(null=True, blank=True, help_text=_("Number of users (individuals) that are eligible to participate in eduroam service"))
    number_id = models.PositiveIntegerField(null=True, blank=True, help_text=_("Number of issued e-identities (credentials) that may be used for authentication in eduroam service"))
    ts = models.DateTimeField(auto_now=True)

    get_address = Address_i18n.get_address_factory('address')
    get_address.short_description = 'Institution Address'

    class Meta:
        verbose_name = "Institutions' Details"
        verbose_name_plural = "Institution Details"

    def __str__(self):
        return _('Institution: %(inst)s, Type: %(ertype)s') % {
            # but name is many-to-many from institution
            'inst': ', '.join([i.name for i in self.institution.org_name.all()]),
            'ertype': self.institution.get_ertype_display(),
        }

    def get_inst_name(self):
        return ", ".join([i.name for i in self.institution.org_name.all()])
    get_inst_name.short_description = "Institution Name"
示例#10
0
class Occurrence(models.Model):
    """
    Represents the start end time for a specific occurrence of a master ``Event``
    object.
    """
    start_time = models.DateTimeField(_('start time'))
    end_time = models.DateTimeField(_('end time'))
    event = models.ForeignKey(Event, verbose_name=_('event'), editable=False, on_delete=models.CASCADE)
    notes = fields.GenericRelation(Note, verbose_name=_('notes'))

    objects = OccurrenceManager()

    class Meta:
        verbose_name = _('occurrence')
        verbose_name_plural = _('occurrences')
        ordering = ('start_time', 'end_time')

    def __unicode__(self):
        return u'%s: %s' % (self.title, self.start_time.isoformat())

    @models.permalink
    def get_absolute_url(self):
        return ('swingtime-occurrence', [str(self.event.id), str(self.id)])

    def __cmp__(self, other):
        return cmp(self.start_time, other.start_time)

    @property
    def title(self):
        return self.event.title

    @property
    def event_type(self):
        return self.event.event_type
示例#11
0
文件: models.py 项目: swpp-team1/c-vs
class Review(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    edited = models.DateTimeField(auto_now=True)
    title = models.CharField(max_length=100)
    rating = fields.GenericRelation('Rating', related_query_name='review')
    user_id = models.ForeignKey(
        'CustomUser',
        on_delete=models.CASCADE,
    )
    product = models.ForeignKey('Product', on_delete=models.CASCADE)
    post = fields.GenericRelation('Post',
                                  related_query_name='review',
                                  null=True)

    class Meta:
        ordering = ('created', )
示例#12
0
class Example(models.Model):
    name = models.CharField('Name of Example', max_length=200)
    num_trial = models.IntegerField('Trial Number')
    alert_color = ColorField('Color of Alert (green default is #4ef442)',
                             default="#f44141")
    points = models.FloatField('Points from Last Trial')
    score = models.FloatField('Score')
    outcome = models.CharField('Outcome from Last Trial', max_length=200)
    stimulus_choices = (('num', 'Numbers'), ('rect', 'Rectangles'))
    stimulus = models.CharField('Choice of Stimulus',
                                max_length=200,
                                choices=stimulus_choices,
                                default='num')
    val = models.FloatField(
        'Value of Stimulus (rectangle value is percent of box height)')
    module = fields.GenericRelation(Module)

    def __str__(self):
        return self.name

    def save(self, *args, **kwargs):
        if not self.pk:
            super(Example, self).save(*args, **kwargs)
            m = Module(content_object=self)
            m.save()
        super(Example, self).save(*args, **kwargs)
示例#13
0
class Department(models.Model):
    objects = QuerySet.as_manager()

    org = models.ForeignKey(Organization, on_delete=models.CASCADE)
    list_order = models.IntegerField(null=True, blank=True)
    name = models.CharField(max_length=50, null=True, blank=True)
    bldg = models.ForeignKey(Building, on_delete=models.CASCADE)
    room = models.CharField(max_length=50, null=True, blank=True)
    phone = models.CharField(max_length=50, null=True, blank=True)
    fax = models.CharField(max_length=50, null=True, blank=True)
    primary_comment = models.TextField(null=True, blank=True)
    secondary_comment = models.TextField(null=True, blank=True)
    last_updated = models.DateTimeField(null=True, blank=True)
    import_id = models.IntegerField(null=True, blank=True)
    keywords = fields.GenericRelation(Keyword)
    active = models.BooleanField(default=True)
    unit = models.ForeignKey(Unit,
                             related_name='teledata_departments',
                             blank=True,
                             null=True,
                             on_delete=models.SET_NULL)

    def __unicode__(self):
        return self.name

    def __str__(self):
        return self.name
示例#14
0
class AbstractResidence(Model):
    """
    This class holds information about a residence in the college
    """

    code = models.CharField(
        max_length=7,
        unique=True,
    )
    name = models.CharField(max_length=127, )

    location_information = contenttypes_fields.GenericRelation(
        to=LocationInformation,
        related_query_name='residence',
        content_type_field='entity_content_type',
        object_id_field='entity_object_id',
    )

    class Meta:
        """
        Meta class for AbstractResidence
        """

        abstract = True

    def __str__(self):
        """
        Return the string representation of the model
        :return: the string representation of the model
        """

        name = self.name
        return f'{name}'
示例#15
0
class ObjectPermissionsMixin(models.Model):
    from django.contrib.contenttypes import fields
    """
    Abstract base class for media groups (Project and View objects).
    """
    access_authority = models.ForeignKey('ObjectAuthority',
                                         db_column='view_authority',
                                         verbose_name='Sharing')
    access_key = models.CharField(max_length=16, null=True, blank=True)
    users = fields.GenericRelation('UserAuthorityObject')

    class Meta:
        abstract = True
        app_label = 'site'

    def __has_user_permissions(self, user, authority_id):
        # anonymous or null users don't have user-level permissions:
        if user is None or not user.is_authenticated():
            return False

        # object owners have blanket view/edit/manage user-level permissions:
        if self.owner == user:
            return True

        # users with privileges which are greater than or equal to
        # the authority_id have user-level permisisons:
        return len(self.users
                   .filter(user=user)
                   .filter(authority__id__gte=authority_id)
                   ) > 0

    def can_view(self, user=None, access_key=None):
        from localground.apps.site.models.permissions import ObjectAuthority, \
            UserAuthority
        # projects and views marked as public are viewable:
        if self.access_authority.id == ObjectAuthority.PUBLIC:
            return True

        # projects and views marked as "PUBLIC_WITH_LINK" that provide
        # the correct access_key are viewable:
        elif self.access_authority.id == ObjectAuthority.PUBLIC_WITH_LINK \
                and self.access_key == access_key:
            return True

        # projects which are accessible by the user are viewable:
        else:
            return self.__has_user_permissions(user, UserAuthority.CAN_VIEW)

    def can_edit(self, user):
        from localground.apps.site.models.permissions import UserAuthority
        return self.__has_user_permissions(user, UserAuthority.CAN_EDIT)

    def can_manage(self, user):
        from localground.apps.site.models.permissions import UserAuthority
        return self.__has_user_permissions(user, UserAuthority.CAN_MANAGE)

    def share_url(self):
        return '/profile/{0}/{1}/share/'.format(
            self.model_name_plural,
            self.id)
示例#16
0
class Affiche(models.Model):
    """
        Une affiche sur la page "médias" d'une association
    """
    association = models.ForeignKey(Association, blank=True, null=True)
    titre = models.CharField(verbose_name='Titre de l\'affiche', max_length=64)
    fichier = models.ImageField(upload_to='affiches')
    date = models.DateField(verbose_name='Date de publication',
                            default=datetime.now,
                            blank=True,
                            null=True)
    notification = fields.GenericRelation(Notification)

    class Meta:
        ordering = ['-date', '-id']

    def __str__(self):
        return self.association.nom + ' - ' + self.titre

    def get_absolute_url(self):
        return self.association.get_absolute_url() + 'medias/'

    def envoyer_notification(self):
        notification = Notification(content_object=self,
                                    description=self.association.nom +
                                    ' a publie une nouvelle affiche')
        notification.save()
        notification.envoyer_multiple(self.association.suivi_par.all())

    def save(self, *args, **kwargs):
        creation = self.pk is None  # Création de l'objet
        super(Affiche, self).save(*args, **kwargs)
        if creation:
            self.envoyer_notification()
示例#17
0
class Institution(models.Model):
    '''
    Institution
    '''

    realmid = models.ForeignKey("Realm")
    org_name = fields.GenericRelation(Name_i18n)
    ertype = models.PositiveIntegerField(choices=ERTYPES, db_column='type')

    def __unicode__(self):
        return "%s" % ', '.join([i.name for i in self.org_name.all()])

    def get_name(self, lang=None):
        name = ', '.join([i.name for i in self.org_name.all()])
        if not lang:
            return name
        else:
            try:
                name = self.org_name.get(lang=lang)
                return name
            except Exception:
                return name

    def get_active_cat_enrl(self):
        urls = []
        active_cat_enrl = self.catenrollment_set.filter(
            url='ACTIVE', cat_instance='production')
        for catenrl in active_cat_enrl:
            if catenrl.cat_configuration_url:
                urls.append(catenrl.cat_configuration_url)
        return urls
示例#18
0
class Book(models.Model):
    LANGUAGE_CHOICE = (('ch', '中文'), ('en', '英文'))
    COUNTRY_CHOICE = (('in', '国内'), ('out', '国外'))
    TYPE_CHOICE = (('1', '教辅'), ('2', '课外'))
    PLACE_CHOICE = (
        ('1', '信息学部'),
        ('2', '文理学部'),
        ('3', '工学部'),
        ('4', '医学部'),
    )
    # 图书所有者
    owner = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='books')
    # 图书名
    name = models.CharField(max_length=20, verbose_name='name')
    # 图书封面照片
    images = models.CharField(max_length=1024,
                              default=settings.PREFIX_URL +
                              settings.QINIU_BUCKET_DOMAIN + '/' +
                              "books/mask.png",
                              verbose_name='image')
    # 图书语言
    language = models.CharField(max_length=2,
                                default='ch',
                                choices=LANGUAGE_CHOICE,
                                verbose_name='language')
    # 图书地界(国内或国外)
    country = models.CharField(max_length=3,
                               default='in',
                               choices=COUNTRY_CHOICE,
                               verbose_name='country')
    # 图书类别(教辅或课外)
    types = models.CharField(max_length=1,
                             default='2',
                             choices=TYPE_CHOICE,
                             verbose_name='types')
    # 地点
    place = models.CharField(max_length=1,
                             default='1',
                             choices=PLACE_CHOICE,
                             verbose_name='place')
    # 图书等级
    level = models.CharField(max_length=4, verbose_name='level')
    # 消息通知
    notice = fields.GenericRelation(Notice)
    # 创建时间
    created_at = models.DateTimeField(auto_now_add=True)
    # 最后一次更改时间
    updated_at = models.DateTimeField(auto_now=True)
    # 交换状态
    status = models.BooleanField(default=False)

    class Meta:
        db_table = 'Book'
        ordering = ['level']

    def __str__(self):
        return self.name

    def description(self):
        return '%s有图书《%s》在平台上等待交换' % (self.owner.nickname, self.name)
class SurveyAnswer(TranslationModelMixin, TranslatableModel):
    """
    Belongs to a SurveyQuestion.

    :title: The title of this answer. Authors may change this title.
    :slug: The slug of this answer. Should never be changed since it might be
      referenced in the code.
    :position: Can be used to order answers.

    """
    translations = TranslatedFields(
        title=models.CharField(verbose_name=_('Title'), max_length=256),
    )

    slug = models.SlugField(
        verbose_name=_('Slug'),
        max_length=256,
    )

    question = models.ForeignKey(
        SurveyQuestion,
        verbose_name=_('Question'),
        related_name='answers'
    )

    generic_position = fields.GenericRelation(
        'generic_positions.ObjectPosition'
    )

    class Meta:
        unique_together = ('slug', 'question')
示例#20
0
class Text(models.Model):
    text = models.TextField()

    contribution = contenttypes.GenericRelation(
        'contributions.Contribution',
        content_type_field='contribution_type',
        object_id_field='contribution_id',
        related_query_name='text')
示例#21
0
class Realm(models.Model):
    '''
    Realm
    '''

    roid = models.CharField(
        max_length=255,
        default=getattr(settings, 'NRO_ROID'),
        unique=True,
        db_column='ROid'
    )
    country = models.CharField(max_length=5, choices=get_choices_from_settings('REALM_COUNTRIES'))
    stype = 0 # hard-coded (FLRS)
    stage = models.PositiveIntegerField(
        choices=PRODUCTION_STATES,
        default=PRODUCTION_STATES.ACTIVE
    )
    # TODO: multiple names can be specified [...] name in English is required
    org_name = fields.GenericRelation(Name_i18n)
    # TODO: multiple addresses can be specified [...] address in English is required
    address = fields.GenericRelation(Address_i18n)
    coordinates = models.ForeignKey(
        Coordinates,
        on_delete=models.SET_NULL,
        blank=True,
        null=True
    )
    contact = models.ManyToManyField(Contact)
    url = fields.GenericRelation(URL_i18n)
    ts = models.DateTimeField(auto_now=True)

    get_address = Address_i18n.get_address_factory('address')
    get_address.short_description = 'Realm Address'

    class Meta:
        verbose_name = "Realm"
        verbose_name_plural = "Realms"

    def __str__(self):
        return _('Country: %(country)s, NRO: %(orgname)s') % {
            # but name is many-to-many from institution
            'orgname': ', '.join([i.name for i in self.org_name.all()]),
            'country': self.country,
        }

    get_name = Name_i18n.get_name_factory('org_name')
示例#22
0
class Project(models.Model):
    pid = models.AutoField(primary_key=True)
    name = models.CharField(max_length=10, unique=True)
    client = models.ForeignKey(Client, on_delete=models.CASCADE, null=True,
                               blank=True)
    members = models.ManyToManyField(get_user_model(), blank=True)
    tags = fields.GenericRelation(Tag)
    created = models.DateTimeField(auto_now_add=True, editable=False)
示例#23
0
class Block(models.Model):
    name = models.CharField('Name of Experiment Block', max_length=200)
    num_trials = models.IntegerField('# Trials', default=5)
    p_signal = models.FloatField('Probability of Signal', default=0.5)
    v_hit_s = models.FloatField(default=1.0)
    v_hit_n = models.FloatField(default=1.5)
    v_miss_s = models.FloatField(default=-1.5)
    v_miss_n = models.FloatField(default=-1.0)
    v_cr_s = models.FloatField(default=0.0)
    v_cr_n = models.FloatField(default=0.0)
    v_fa_s = models.FloatField(default=0.0)
    v_fa_n = models.FloatField(default=0.0)
    v_na = models.FloatField('Payoff Value of N/A (did not complete in time)',
                             default=0.0)
    d_user = models.FloatField("User Sensitivity (d')", default=1.0)
    d_alert = models.FloatField("Alert Sensitivity (d')", default=1.0)
    beta_alert = models.FloatField("Alert Criterion (beta)", default=0.5)
    mean = models.FloatField('Mean (between signal/noise distributions)',
                             default=5.0)
    sd = models.FloatField('Standard Deviation', default=0.5)
    stimulus_choices = (('num', 'Numbers'), ('rect', 'Rectangles'))
    stimulus = models.CharField('Choice of Stimulus',
                                max_length=200,
                                choices=stimulus_choices,
                                default='num')
    num_dec_places = models.IntegerField(
        '# Decimal Places to Use for Stimulus', default=1)
    alert_signal_color = ColorField('Alert Color for Signal',
                                    default="#f44141")
    alert_noise_color = ColorField('Alert Color for Noise', default="#4ef442")
    stimulus_duration = models.FloatField('Stimulus Duration (seconds)',
                                          default=5.0)
    stimulus_delay = models.FloatField('Stimulus Delay (seconds)', default=0.0)
    alert_duration = models.FloatField('Alert Duration (seconds)', default=5.0)
    alert_delay = models.FloatField('Alert Delay (seconds)', default=0.0)
    trial_duration = models.FloatField('Total Trial Duration (seconds)',
                                       default=5.0)
    trial_delay = models.FloatField('Delay Between Trials (seconds)',
                                    default=3.0)
    display_last_points = models.BooleanField('Display Points from Last Trial',
                                              default=True)
    display_outcome = models.BooleanField('Display Outcome from Last Trial',
                                          default=True)
    display_total_points = models.BooleanField('Display Cumulative Points',
                                               default=True)
    display_trial_num = models.BooleanField('Display Number of Trial in Block',
                                            default=True)
    module = fields.GenericRelation(Module)

    def __str__(self):
        return self.name

    def save(self, *args, **kwargs):
        if not self.pk:
            super(Block, self).save(*args, **kwargs)
            m = Module(content_object=self)
            m.save()
        super(Block, self).save(*args, **kwargs)
示例#24
0
class DummyParentModel(models.Model):
    """Dummy to be used in test cases of the ``generic_positions`` app."""
    name = models.CharField(max_length=256, blank=True)

    generic_position = fields.GenericRelation(
        'generic_positions.ObjectPosition')

    def __unicode__(self):
        return self.name
示例#25
0
class Staff(models.Model):
    objects = QuerySet.as_manager()

    alpha = models.BooleanField(default=True, null=False, blank=False)
    last_name = models.CharField(max_length=25, null=False, blank=False)
    suffix = models.CharField(max_length=3, null=True, blank=True)
    name_title = models.CharField(max_length=10, null=True, blank=True)
    first_name = models.CharField(max_length=14, null=False, blank=False)
    employee_id = models.CharField(max_length=8, null=True, blank=True)
    middle = models.CharField(max_length=15, null=True, blank=True)
    dept = models.ForeignKey(Department, on_delete=models.CASCADE)
    job_position = models.CharField(max_length=100, null=True, blank=True)
    bldg = models.ForeignKey(Building, on_delete=models.CASCADE)
    room = models.CharField(max_length=255, null=True, blank=True)
    phone = models.CharField(max_length=255, null=True, blank=True)
    email = models.EmailField(max_length=100, null=True, blank=True)
    email_machine = models.CharField(max_length=255, null=True, blank=True)
    postal = models.CharField(max_length=10, null=True, blank=True)
    last_updated = models.DateTimeField(null=True, blank=True)
    cellphone = models.CharField(max_length=50, null=True, blank=True)
    keywords = fields.GenericRelation(Keyword)
    import_id = models.IntegerField(null=True, blank=True)
    active = models.BooleanField(default=True)

    @property
    def full_name_formatted(self):
        retval = self.last_name

        if self.suffix:
            retval += ' {0}'.format(self.suffix)

        retval += ','

        if self.name_title:
            retval += ' {0}'.format(self.name_title)

        retval += ' {0}'.format(self.first_name)

        if self.middle:
            retval += ' {0}'.format(self.middle)

        return retval

    @property
    def name(self):
        return '{0} {1}'.format(self.first_name, self.last_name)

    @property
    def sort_name(self):
        return '{0} {1}'.format(self.last_name, self.first_name)

    def __unicode__(self):
        return self.name

    def __str__(self):
        return self.name
示例#26
0
class Car(ChangesTrackingMixin):
    car_mark = models.ForeignKey(CarMark)
    car_model = models.ForeignKey(CarModel)
    credential = contenttype_fields.GenericRelation(Credential)
    engine_power = models.PositiveIntegerField()
    engine_power_kilowatt = models.FloatField()
    manufacturing_date = models.PositiveIntegerField()
    mileage = models.PositiveIntegerField()
    number_plate = models.CharField(max_length=9)
    vin_number = models.CharField(max_length=17)
示例#27
0
class Tag(models.Model):
    title = models.CharField(max_length=20, default='tag')
    tags = fields.GenericRelation(TagItem, content_type_field='content_type_fk', object_id_field='object_primary_key')

    class Meta:
        verbose_name = 'Тег'
        verbose_name_plural = 'Теги'

    def __str__(self):
        return self.title
示例#28
0
class Sondage(models.Model):
    auteur = models.ForeignKey(UserProfile)
    question = models.CharField(max_length=512)
    reponse1 = models.CharField(max_length=200)
    reponse2 = models.CharField(max_length=200)
    deja_paru = models.BooleanField()
    date_parution = models.DateField(null=True, blank=True)
    autorise = models.BooleanField()
    resultat = models.IntegerField(editable=False)
    weight_score = models.FloatField(editable=False, null=True)
    objects = SondageManager()

    notification = fields.GenericRelation(Notification)

    def date_str(self):
        jour = str(self.date_parution.day)
        mois = str(self.date_parution.month)
        if self.date_parution.day < 10:
            jour = '0' + jour
        if self.date_parution.month < 10:
            mois = '0' + mois
        return jour + '/' + mois + '/' + str(self.date_parution.year)

    def __str__(self):
        return self.question

    # renvoie le resultat du sondage (1 ou 2 selon la reponse ayant le plus de votes)
    def calculer_resultat(self):
        from django.db.models import Count
        votes = Vote.objects.filter(sondage=self)
        if votes:
            return votes.values('choix').annotate(
                c=Count('choix')).order_by('-c')[0]['choix']
        else:
            return 0

    def envoyer_notification(self):
        try:
            perm = Permission.objects.get(
                codename='add_sondage'
            )  #On envoie seulement à ceux qui peuvent créer des sondages
            users = User.objects.filter(
                Q(is_superuser=True) | Q(groups__permissions=perm)
                | Q(user_permissions=perm)).distinct()
            notification = Notification(
                content_object=self,
                description='Un nouveau sondage a été proposé')
            notification.save()
            notification.envoyer_multiple(users)
        except Permission.DoesNotExist:
            pass

    def save(self, *args, **kwargs):
        self.resultat = self.calculer_resultat()
        super(Sondage, self).save(*args, **kwargs)
示例#29
0
class SampleData(Base):
    sample = models.ForeignKey(Sample)
    data = JSONField()
    notes = fields.GenericRelation(Note)

    class Meta:
        app_label = "core"
        db_table = 'sample_data'
        verbose_name_plural = 'sample data'

    def __str__(self):
        return self.action
示例#30
0
class Aportes(models.Model):
	foro = models.ForeignKey(Foros,on_delete=models.CASCADE)
	fecha = models.DateField(auto_now_add=True)
	contenido = RichTextUploadingField()
	user = models.ForeignKey(User,on_delete=models.DO_NOTHING)
	adjuntos = fields.GenericRelation(Documentos)
	fotos = fields.GenericRelation(Imagen)
	video = fields.GenericRelation(Videos)
	audio = fields.GenericRelation(Audios)

	class Meta:
		verbose_name_plural = "Aportes"

	def __str__(self):
		return self.foro.nombre
		
	def __documento__(self):
		lista = []
		for obj in self.adjuntos.all():
			lista.append(obj)
		return lista

	def __fotos__(self):
		lista = []
		for obj in self.fotos.all():
			lista.append(obj)
		return lista

	def __video__(self):
		lista = []
		for obj in self.video.all():
			lista.append(obj)
		return lista

	def __audio__(self):
		lista = []
		for obj in self.audio.all():
			lista.append(obj)
		return lista