コード例 #1
0
ファイル: models.py プロジェクト: camoguard/proto
class Video(models.Model):
    title = models.CharField(max_length=70)
    deck = models.CharField(max_length=100)
    category = models.ForeignKey('VideoCategory')
    file = models.FileField(upload_to='videos')
    image = models.ImageField(upload_to='images/videos')
    pub_date = models.DateTimeField()
    status = models.CharField(max_length=1, choices=STATUS_CHOICES)
    premium = models.BooleanField(default=False)
    tags = models.ManyToManyField(Wiki, null=True, blank=True)
    comments = generic.GenericRelation(ThreadedComment,
                                       object_id_field='object_pk')
    site = models.ForeignKey(Site)
    created = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)

    objects = models.Manager()
    on_site = CurrentSiteManager()
    public = PublicManager()

    class Meta:
        ordering = ['-pub_date']

    def __unicode__(self):
        return self.title
コード例 #2
0
class Profile(models.Model):
    user = models.OneToOneField(User, related_name='profile')
    public_profile = models.BooleanField(default=True)
    gender = models.CharField(max_length=1,
                              choices=GENDER_CHOICES,
                              blank=True,
                              null=True)
    bio = models.TextField(null=True, blank=True)
    description = lambda self: self.bio
    email_notification = models.CharField(max_length=1,
                                          choices=NOTIFICATION_PERIOD_CHOICES,
                                          blank=True,
                                          null=True,
                                          default='D')
    avatar_uri = models.URLField(null=True, blank=True)
    last_email_update = models.DateTimeField(default=NEVER_SENT)
    locality = models.ForeignKey(Entity, null=True, verbose_name=_('Locality'))
    sites = models.ManyToManyField(Site)
    is_editor = models.BooleanField(default=False)
    verification = models.CharField(max_length=1,
                                    choices=VERIFICATION_STAGES,
                                    default='0')
    on_site = CurrentSiteManager()

    objects = ProfileManager()

    def __unicode__(self):
        return self.user.get_full_name()

    @property
    def following(self):
        return map(
            lambda x: x.actor,
            Follow.objects.filter(user=self.user).prefetch_related('actor'))

    def get_absolute_url(self):
        return reverse('public-profile', args=(self.user.username, ))

    def get_full_name(self):
        return self.user.get_full_name() or self.user.username

    @cached_property
    def is_candidate(self):
        return self.user.candidate_set.exists()

    @cached_property
    def is_mayor_candidate(self):
        try:
            return Candidate.objects.only('for_mayor').get(
                user=self.user).for_mayor
        except:
            return False

    @cached_property
    def candidate_list(self):
        try:
            return Candidate.objects.only('candidate_list').get(
                user=self.user).candidate_list
        except:
            return None
コード例 #3
0
class Solution(models.Model):
  ownership = models.ForeignKey(Ownership, blank=True, null=True, default=None, related_name='solution_ownership')
  owner_ct = models.ForeignKey(ContentType, related_name='solution_owner')
  owner_id = models.PositiveIntegerField()
  owner_own = models.ForeignKey(Ownership, related_name='solution_owner_own')
  source = models.ForeignKey(Source)
  category =  models.ForeignKey(Category)
  problem = models.CharField(max_length=200)
  problem_desc = models.TextField()
  solution = models.TextField()
  tags = models.ManyToManyField(Tag, related_name='solution_tags')
  votes_sum = models.BigIntegerField(blank=True, null=True, default=0)
  votes_count = models.BigIntegerField(blank=True, null=True, default=0)
  viewed = models.BigIntegerField(blank=True, null=True, default=0)
  datetime_added = models.DateTimeField(default=datetime.datetime.now)
  is_published = models.BooleanField(default=True)
  is_suspended = models.BooleanField(default=False)
  is_deleted = models.BooleanField(default=False)
  
  owner = generic.GenericForeignKey('owner_ct', 'owner_id')

  site = models.ForeignKey(Site,default=1)
  objects = models.Manager()
  on_site = CurrentSiteManager()

  objects = SolutionManager()

  def get_absolute_url(self):
    return "/solutions/view/%i/" % self.id
  
  def __unicode__(self):
    return '%s, %s'%(self.id, self.problem)
コード例 #4
0
ファイル: models.py プロジェクト: BramaBrama/spicy.core
class SiteTrashModel(TrashModel):
    objects = SiteNonTrashManager()
    deleted_objects = SiteTrashManager()
    all_objects = CurrentSiteManager()

    class Meta:
        abstract = True
コード例 #5
0
ファイル: event.py プロジェクト: suselrd/django-notifications
class Event(models.Model):
    type = models.ForeignKey(EventType)
    user = models.ForeignKey(User, related_name='events')
    date = models.DateTimeField(auto_now_add=True)

    target_type = models.ForeignKey(ContentType, verbose_name=_('target type'), related_name="%(class)s")
    target_pk = models.TextField(_('target ID'))
    target_object = GenericForeignKey(ct_field="target_type", fk_field="target_pk")

    extra_data = JSONField(null=True, blank=True)
    details = models.TextField(max_length=500)

    site = models.ForeignKey(Site, null=True)

    objects = models.Manager()
    on_site = CurrentSiteManager()

    class Meta:
        app_label = 'notifications'

    def __unicode__(self):
        return self.details

    def get_related_obj_by_role_name(self, role_name):
        try:
            role = EventObjectRole.objects.get(name=role_name)
            related_objects = self.eventobjectrolerelation_set.filter(role=role)
            if len(related_objects):
                return related_objects[0].target_object
            return None
        except EventObjectRole.DoesNotExist:
            return None
コード例 #6
0
class TargetNodesSite(models.Model):
    site = models.ForeignKey(Site)
    node = models.ForeignKey(Node)
    on_site = CurrentSiteManager()

    def __unicode__(self):
        return u'%s' % self.node
コード例 #7
0
class Entry(models.Model):
    class Meta:
        verbose_name_plural = "Entries"
        ordering = ["-date", "-id"]

    description = models.CharField(max_length=300)
    date = models.DateField(default=datetime.date.today())
    site = models.ForeignKey(Site)

    objects = CurrentSiteManager()
    
    def __unicode__(self):
        return u"Entry #%s %s" % (self.id, self.date)
    
    def debits(self):
        return self.entryaction_set.filter(amount__gte=0)
    
    def credits(self):
        return self.entryaction_set.filter(amount__lt=0)

    def total(self):
        total = 0
        for debit in self.debits():
            total += debit.amount
        return total

    def error(self):
        total = 0
        for debit in self.entryaction_set.all():
            total += debit.amount
        if abs(floor(total)) > 0:
            return "Error!: %.0f" % total# != 0.0
        else:
            return ""
コード例 #8
0
ファイル: models.py プロジェクト: xuanxu11/PyLucid
class PyLucidComment(Comment):
    notify = models.BooleanField(
        help_text=
        "Send me a mail if someone replay on my comment. (Needs a email address ;)"
    )

    on_site = CurrentSiteManager()

    def get_absolute_url(self):
        return self.content_object.get_absolute_url()

    def get_update_info(self):
        """ update info for update_journal.models.UpdateJournal used by update_journal.save_receiver """
        if self.is_public == False or self.is_removed == True:  # Don't list non public articles
            return

        return {
            "lastupdatetime": self.submit_date,
            "user_name": self.userinfo["name"],
            "language": self.content_object.language,
            "object_url": self.get_absolute_url(),
            "title": "New comment for '%s'" % self.content_object.get_name(),
        }

    class Meta:
        verbose_name = _('PyLucid comment')
        verbose_name_plural = _('PyLucid pylucid_comments')
コード例 #9
0
class Video(models.Model):
    title = models.CharField(max_length=255)
    url = models.CharField(max_length=255)
    description = models.TextField()
    author = models.CharField(max_length=255)
    date = models.DateField(null=True)
    people = models.ManyToManyField(People, blank=True)
    VIDEOSITES = (
        ('youtube', 'YouTube'),
        ('vimeo', 'Vimeo'),
        ('wikimedia', 'Wikimedia Commons'),
        ('other', 'Other website'),
    )

    website = models.CharField(max_length=20, choices=VIDEOSITES)
    site = models.ForeignKey(Site, on_delete=models.CASCADE, default=settings.SITE_ID)
    objects = models.Manager()
    on_site = CurrentSiteManager()
    primary_space = models.ForeignKey(ReferenceSpace, on_delete=models.CASCADE, null=True, blank=True)
    collections = models.ManyToManyField(VideoCollection, blank=True)
    thumbnail = models.ImageField(null=True, blank=True, upload_to='video_thumbnails')
    license = models.ForeignKey(License, on_delete=models.CASCADE, null=True, blank=True)

    def __str__(self):
        return self.title
コード例 #10
0
ファイル: models.py プロジェクト: guilhermebr/opps
class Publisher(Date):

    site = models.ForeignKey(Site, default=1)
    site_iid = models.PositiveIntegerField(_(u"Site id"),
                                           max_length=4,
                                           null=True,
                                           blank=True,
                                           db_index=True)
    site_domain = models.CharField(_(u"Site domain"),
                                   max_length=100,
                                   null=True,
                                   blank=True,
                                   db_index=True)
    date_available = models.DateTimeField(_(u"Date available"),
                                          default=timezone.now,
                                          null=True,
                                          db_index=True)
    published = models.BooleanField(_(u"Published"),
                                    default=False,
                                    db_index=True)

    objects = PublishableManager()
    on_site = CurrentSiteManager()

    class Meta:
        abstract = True

    def save(self, *args, **kwargs):
        self.site_domain = self.site.domain
        self.site_iid = self.site.id
        super(Publisher, self).save(*args, **kwargs)

    def is_published(self):
        return self.published and self.date_available <= timezone.now()
コード例 #11
0
ファイル: models.py プロジェクト: RuhiuEdwin/catalog
class Category(models.Model):
    """A category of Items in the Catalog"""
    name = models.CharField(max_length=128)
    slug = models.SlugField(unique=True)
    order = models.IntegerField(default=100)
    sites = models.ManyToManyField(Site)
    
    all_objects = models.Manager()
    objects = CurrentSiteManager("sites")
    
    def site_item_set(self):
        return self.item_set.all().filter(sites=Site.objects.get_current()).exclude(mainitem=None)

    class Meta:
        ordering = ['order', 'name']
        verbose_name, verbose_name_plural = _("category"), _("categories")
        
    def sites_display(self):
        l = []
        for site in self.sites.all():
            l.append(site.name)
        return ", ".join(l)

    def __unicode__(self):
        return self.name
        
    @models.permalink
    def url(self):
        return ('category_detail', (self.slug,), {})
    get_absolute_url = url
コード例 #12
0
class Kurs(UpdateInfoBaseModel):
    """   
    e.g.:
    3dsmax - SS 2009 - Vormittags (9-12 Uhr)
    3dsmax - SS 2009 - Nachmittags (13-16 Uhr)

    inherited attributes from UpdateInfoBaseModel:
        createtime     -> datetime of creation
        lastupdatetime -> datetime of the last change
        createby       -> ForeignKey to user who creaded this entry
        lastupdateby   -> ForeignKey to user who has edited this entry
    """
    name = models.CharField(
        verbose_name="Kurs", help_text="Der Kursname",
        max_length=255, unique=True,
    )
    active = models.BooleanField(
        help_text="Ist der Kurs aktiv buchbar?"
    )

    site = models.ForeignKey(Site, editable=False, default=settings.SITE_ID)
    on_site = CurrentSiteManager('site')

    def __unicode__(self):
        return u"Kurs %s" % (self.name)

    class Meta:
        verbose_name_plural = "Kurse"
コード例 #13
0
ファイル: models.py プロジェクト: EvilX/django-snippets
class Snippet(models.Model):
    """
    Think of a Snippet as a part of a template. It's basically a piece
    of content with a given name (slug), that can be included and
    rendered with a template with templatetag ``include_snippet``.
    """
    slug = models.CharField(
        _('slug'),
        max_length=255,
        unique=True,
        help_text=_('A unique name used for reference in the templates'))
    content = models.TextField(_('content'), blank=True, null=True)
    sites = models.ManyToManyField(Site, default=[settings.SITE_ID])

    objects = models.Manager()
    on_site = CurrentSiteManager('sites')

    class Meta:
        verbose_name = _('snippet')
        verbose_name_plural = _('snippets')
        ordering = ('slug', )
        app_label = 'snippets'

    def __unicode__(self):
        return u'%s' % (self.slug, )
コード例 #14
0
class Answer(BaseModel):
    author = models.ForeignKey(User,
                               related_name="answers",
                               verbose_name=_("author"))
    content = models.TextField(
        _("content"),
        max_length=MAX_LENGTH_A_CONTENT,
        help_text=_("Please enter an answer in no more than %s letters") %
        MAX_LENGTH_A_CONTENT)
    rating = models.IntegerField(_("rating"), default=0)
    question = models.ForeignKey(Question,
                                 related_name="answers",
                                 verbose_name=_("question"))
    sites = models.ManyToManyField(Site)
    # for easy access to current site answers
    objects = models.Manager()
    on_site = CurrentSiteManager()

    def __unicode__(self):
        return "%s: %s" % (self.author, self.content[:30])

    def get_absolute_url(self):
        return '%(url)s?answer=%(id)s#answer-%(id)s' % {
            'url': self.question.get_absolute_url(),
            'id': self.id
        }
コード例 #15
0
class Genre(models.Model):
    code = models.SlugField(max_length=50,
                            null=True,
                            blank=True,
                            editable=False)
    name = models.CharField(max_length=50,
                            help_text="Enter a book genre",
                            unique=True)
    description = models.TextField(max_length=1000, null=True, blank=True)
    image = models.ImageField(
        upload_to='{0}/genre/'.format(settings.MEDIA_ROOT),
        help_text="Images to be uploaded here will be resized to 1000x300",
        null=True,
        blank=True)
    site = models.ForeignKey(Site, on_delete=models.CASCADE)
    objects = models.Manager()
    on_site = CurrentSiteManager()

    def __str__(self):
        return self.name

    def save(self, *args, **kwargs):
        self.code = slugify(self.name)
        if self.image:
            self.image = functions.resize(self.image, 1000, 300)
        super(Genre, self).save(*args, **kwargs)
コード例 #16
0
class FeedItem(models.Model):
    user = models.ForeignKey(User)
    role = models.CharField(max_length=100, null=True, blank=True)
    event = models.ForeignKey(Event)
    template_config = models.ForeignKey(NotificationTemplateConfig)
    context = models.CharField(default=u'default', max_length=255)
    seen = models.BooleanField(default=False)

    site = models.ForeignKey(Site)

    objects = models.Manager()
    on_site = CurrentSiteManager()

    def __init__(self, *args, **kwargs):
        super(FeedItem, self).__init__(*args, **kwargs)
        if not self.pk and not self.site_id:
            self.site_id = self.event.site_id or Site.objects.get_current().pk

    class Meta:
        app_label = 'notifications'
        unique_together = ('user', 'event', 'context')

    def __unicode__(self):
        return u"For %s - %s %s - %s" % (
            self.user.get_full_name() or self.user.username,
            self.event.user.username,
            self.event.type.name,
            unicode(self.event.target_object)
        )
コード例 #17
0
class Project(CreateUpdateModelBase):
    """
    The Project the release notes are for.
    """
    uuid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True)
    name = models.CharField(_("Name"), max_length=80, blank=False)
    site = models.ForeignKey(Site, verbose_name=_("Site"), on_delete=models.CASCADE, default=get_default_site, related_name="projects")
    slug = models.SlugField(_("Slug"))

    objects = models.Manager()
    on_site = CurrentSiteManager()

    class Meta:
        verbose_name = _("Project")
        verbose_name_plural = _("Projects")

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse("releasenotes:project-details", kwargs={"project_slug": self.slug})

    def save(self, *args, **kwargs):
        value = self.name
        self.slug = slugify(value, allow_unicode=True)      # Add check to make sure it's unique on the site
        super().save(*args, **kwargs)
コード例 #18
0
class Question(BaseModel):

    # TODO: rename to just `slug`
    unislug = models.CharField(_('unicode slug'),
                               max_length=MAX_LENGTH_Q_SUBJECT,
                               null=True,
                               blank=True,
                               editable=False)
    author = models.ForeignKey(User,
                               related_name="questions",
                               verbose_name=_("author"))
    subject = models.CharField(_("question"), max_length=MAX_LENGTH_Q_SUBJECT)
    content = models.TextField(
        _("details"),
        max_length=MAX_LENGTH_Q_CONTENT,
        help_text=_("Please enter your content in no more than %s letters") %
        MAX_LENGTH_Q_CONTENT,
        blank=True,
        default='')
    rating = models.IntegerField(_("rating"), default=1)
    flags_count = models.IntegerField(_("flags counter"), default=0)
    tags = TaggableManager(through=TaggedQuestion, blank=True)
    sites = models.ManyToManyField(Site)
    # for easy access to current site questions
    objects = models.Manager()
    on_site = CurrentSiteManager()
    entity = models.ForeignKey(Entity, null=True, related_name="questions")

    class Meta:
        unique_together = ('unislug', 'entity')

    def __unicode__(self):
        return self.subject

    def can_answer(self, user):
        ''' Can a given user answer self? '''
        if user.is_authenticated():
            profile = user.profile
            return profile.is_candidate and profile.locality == self.entity
        else:
            return False

    def get_absolute_url(self):
        return reverse('question_detail',
                       kwargs=dict(
                           entity_slug=self.entity.slug,
                           slug=self.unislug,
                       ))

    def save(self, **kwargs):
        # make a unicode slug from the subject
        self.unislug = unislugify(self.subject)
        return super(Question, self).save(**kwargs)

    @transaction.commit_on_success
    def flagged(self):
        self.flags_count += 1
        self.save()
        return self.flags_count
コード例 #19
0
class Setting(PolymorphicModel, TranslatableModel):
    """
    A setting for a site
    """

    site = models.ForeignKey(Site)
    key = models.ForeignKey(
        Key,
        error_messages={
            'too_many_for_key':
            _("The %(key_name)s only allows a single value per site."),
        })
    weight = models.IntegerField(_('weight'), default=0)

    objects = SettingManager()
    on_site = CurrentSiteManager()

    def __str__(self):
        return '{} {}'.format(self.site.name, self.key.name)

    def site_name(self):
        return self.site.name

    site_name.short_description = _('site')
    site_name.admin_order_field = 'site__name'

    def clean(self, *args, **kwargs):
        super(Setting, self).clean(*args, **kwargs)

        if self.key.allow_multiples:
            return

        errors = {}

        settings_count = Setting.objects.filter(
            site=self.site, key=self.key).exclude(pk=self.pk).count()

        if settings_count > 0:
            err = ValidationError(
                message=self.key.field.error_messages['too_many_for_key'],
                code='too_many_for_key',
                params={
                    'key_name': self.key.name,
                },
            )
            errors.setdefault('key', []).append(err)

        if errors:
            raise ValidationError(errors)

    class Meta:
        verbose_name = _('Site setting')
        verbose_name_plural = _('Site settings')
        ordering = (
            'site',
            'key',
            '-weight',
        )
        index_together = ['site', 'key']
コード例 #20
0
class Template(models.Model):
    """
    Defines a template model for use with the database template loader.
    The field ``name`` is the equivalent to the filename of a static template.
    """
    name = models.CharField(_('name'), max_length=100,
                            help_text=_("Example: 'flatpages/default.html'"))
    title = models.CharField(
        _('title'), max_length=100, default='', blank=True,
        help_text=_("The title of this template, used for display only.")
    )
    category = models.CharField(
        _('category'), max_length=50, default='', blank=True,
        help_text=_(
            "The category for this template, "
            "useful if you want to organize your templates."
        )
    )
    content = models.TextField(_('content'), blank=True)
    sites = models.ManyToManyField(Site, verbose_name=_(u'sites'),
                                   blank=True)
    creation_date = models.DateTimeField(_('creation date'),
                                         default=now)
    last_changed = models.DateTimeField(_('last changed'),
                                        default=now)

    objects = models.Manager()
    on_site = CurrentSiteManager('sites')

    class Meta:
        db_table = 'django_template'
        verbose_name = _('template')
        verbose_name_plural = _('templates')
        ordering = ('name',)

    def __str__(self):
        return self.title or self.name

    def populate(self, name=None):
        """
        Tries to find a template with the same name and populates
        the content field if found.
        """
        if name is None:
            name = self.name
        try:
            source = get_template_source(name)
            if source:
                self.content = source
        except TemplateDoesNotExist:
            pass

    def save(self, *args, **kwargs):
        self.last_changed = now()
        # If content is empty look for a template with the given name and
        # populate the template instance with its content.
        if settings.DBTEMPLATES_AUTO_POPULATE_CONTENT and not self.content:
            self.populate()
        super(Template, self).save(*args, **kwargs)
コード例 #21
0
class CrfModelMixin(CrfNoManagerModelMixin):

    on_site = CurrentSiteManager()
    objects = CrfModelManager()
    history = HistoricalRecords(inherit=True)

    class Meta(CrfNoManagerModelMixin.Meta):
        abstract = True
コード例 #22
0
ファイル: models.py プロジェクト: Birama0810/Django
class AbstractArticle(models.Model):
    title = models.CharField(max_length=50)

    objects = models.Manager()
    on_site = CurrentSiteManager()

    class Meta:
        abstract = True
コード例 #23
0
class Profile(models.Model):
    user = models.OneToOneField(User, related_name='profile')
    public_profile = models.BooleanField(default=True)
    gender = models.CharField(max_length=1,
                              choices=GENDER_CHOICES,
                              blank=True,
                              null=True)
    bio = models.TextField(null=True, blank=True)
    description = lambda self: self.bio
    email_notification = models.CharField(max_length=1,
                                          choices=NOTIFICATION_PERIOD_CHOICES,
                                          blank=True,
                                          null=True,
                                          default='D')
    avatar_uri = models.URLField(null=True, blank=True)
    url = models.URLField(null=True, blank=True)
    last_email_update = models.DateTimeField(default=NEVER_SENT)
    locality = models.ForeignKey(Entity, null=True, verbose_name=_('Locality'))
    sites = models.ManyToManyField(Site)
    is_candidate = models.BooleanField(default=False)
    is_editor = models.BooleanField(default=False)
    verification = models.CharField(max_length=1,
                                    choices=VERIFICATION_STAGES,
                                    default='0')
    on_site = CurrentSiteManager()

    objects = ProfileManager()

    def avatar_url(self, size=40):
        if self.avatar_uri:
            return self.avatar_uri
        ''' getting the avatar image url from Gravatar '''
        default = "http://oshot.hasadna.org.il/static/img/defaultavatar.png"
        email = self.user.email
        if self.avatar_uri:
            return self.avatar_uri

        if email:
            gravatar_url = "http://www.gravatar.com/avatar/" + hashlib.md5(
                email.lower()).hexdigest() + "?"
            gravatar_url += urllib.urlencode({'d': default, 's': str(size)})
            return gravatar_url
        else:
            return default

    @property
    def following(self):
        return map(lambda x: x.actor,
            Follow.objects.filter(
                user=self.user,
                content_type=ContentType.objects.\
                              get_for_model(settings.AUTH_MODEL)).\
                               prefetch_related('actor')
            )

    def get_absolute_url(self):
        return reverse('public-profile', args=(self.user.username, ))
コード例 #24
0
ファイル: models.py プロジェクト: adreyer/arkestrator
class Thread(models.Model):
    """ a Thread """

    class Meta:
        permissions=(
            ('can_sticky', 'Can sticky threads'),
            ('can_lock', 'Can lock threads'),
            )

    subject = models.CharField(max_length=160, blank=False)
    creator = models.ForeignKey(User,null=False,related_name='threads')
    last_post = models.ForeignKey("board.Post", null=True, 
        related_name='last_post_on')
    stuck = models.BooleanField(default=False)
    locked = models.BooleanField(default=False)
    site = models.ForeignKey(Site, null=False)
    last_read = models.ManyToManyField(User,
        through = 'LastRead',
        related_name='last_read')
    objects = CurrentSiteManager()

    def __unicode__(self):
        return self.subject

    def search_title(self):
        return self.subject

    def search_info(self):
        return None

    @instance_memcache('default-posts-list', 1800)
    def default_post_list(self):
        """ the last ten posts made """

        post_list = self.post_set.select_related('creator').order_by("id")
        post_list = post_list[max(0,post_list.count()-10):]
        return post_list

    @instance_memcache('total-posts', 1800)
    def total_posts(self):
        """ how many posts does a thread have """
        if getattr(self, 'post__count', None):
            return self.post__count
        return self.post_set.count()

    @instance_memcache('total-views', 1800)
    def total_views(self):
        """ how many times has a thread been viewed """

        if getattr(self, 'lastread__read_count__sum', None):
            return self.lastread__read_count__sum
        queryset = LastRead.objects.filter(thread=self)
        agg = queryset.aggregate(models.Sum('read_count'))
        total = agg['read_count__sum']
        if not total:
            return 0
        return total
コード例 #25
0
class SiteAbstract(models.Model):

    site = models.ForeignKey(Site, default=settings.SITE_ID, editable=False)

    onsite = CurrentSiteManager()
    objects = models.Manager()

    class Meta:
        abstract = True
コード例 #26
0
class Category(BaseModel, BaseHeaderImageModel):
    class CategoryWidth(models.TextChoices):
        FULL = "full", _("Fullwidth")
        HALF = "half", _("Half")

    @property
    def category_image_directory_path(self):
        return f"media/categories/{slugify(self.name)}"

    UPLOAD_PATH = category_image_directory_path

    name = models.CharField(_("Category name"), max_length=255, unique=False)
    slug = models.SlugField(
        _("Slug"),
        max_length=50,
        help_text=
        _("A slug is a short label for something, containing only letters, numbers, underscores or hyphens. They’re generally used in URLs."
          ),
    )
    ordering = models.PositiveSmallIntegerField(
        _("Order"),
        help_text=_("Order  in which the category should be displayed."),
        blank=True,
        default=0,
    )
    width = models.CharField(
        _("Width"),
        max_length=4,
        choices=CategoryWidth.choices,
        default=CategoryWidth.FULL,
        blank=True,
        null=True,
    )
    display_in_navbar = models.BooleanField(
        _("Display in navigation bar"),
        default=True,
        help_text=
        _("Designates whether the category should be displayed in the nav dropdown."
          ),
    )
    is_active = models.BooleanField(
        _("Active"),
        default=True,
        help_text=_(
            "Designates whether the category should be treated as active."),
    )
    sites = models.ManyToManyField(Site, related_name="categories", blank=True)

    objects = models.Manager()
    on_site = CurrentSiteManager()

    class Meta:
        verbose_name = _("Category")
        verbose_name_plural = _("Categories")

    def __str__(self):
        return self.name
コード例 #27
0
class BaseFeedbackAbstractModel(DynamicBackendFeedback):
    site = models.ForeignKey(Site,
                             verbose_name=_('Site'),
                             default=Site.objects.get_current)
    pattern = models.ForeignKey('feedback.FeedbackPattern',
                                blank=True,
                                null=True,
                                verbose_name=_('Fedback pattern'))

    processing_status = models.PositiveSmallIntegerField(
        _('Processing status'),
        max_length=1,
        choices=defaults.STATUS_TYPE_CHOICES,
        default=defaults.STATUS_DEFAULT)
    name = models.CharField(_('Name'), max_length=50, blank=True, default='')
    email = models.EmailField(_('Email'),
                              max_length=255,
                              blank=True,
                              default='')
    phone = models.CharField(_('Phone'), max_length=20, blank=True, default='')
    var1 = models.CharField(_('Var 1'), max_length=255, blank=True, default='')
    var2 = models.CharField(_('Var 2'), max_length=255, blank=True, default='')
    var3 = models.CharField(_('Var 3'), max_length=255, blank=True, default='')
    message = models.TextField(_('Message'),
                               max_length=defaults.EMAIL_MAX_LENGTH,
                               blank=True,
                               default='')
    submit_date = models.DateTimeField(_('Submit date'), auto_now_add=True)
    ip_address = models.IPAddressField(_('IP address'), blank=True, null=True)
    company_name = models.CharField(_('Company name'),
                                    max_length=100,
                                    blank=True,
                                    default='')
    url = models.URLField(_('Site URL'), blank=True, default='')

    on_site = CurrentSiteManager()
    objects = models.Manager()

    class Meta:
        db_table = 'fb_feedback'
        ordering = ['-submit_date']
        permissions = [('admin_feedback', 'Admin feedback')]
        abstract = True
        verbose_name = _('Feedback')

    @models.permalink
    def get_admin_url(self):
        return 'feedback:admin:edit', [self.id], {}

    def get_content_object_url(self):
        """
        Get a URL suitable for redirecting to the content object.
        """
        return "TODO:URL"

    def __unicode__(self):
        return '%s @ %s' % (self.name, self.submit_date)
コード例 #28
0
class Slugged(models.Model):
    """
    Abstract model that handles auto-generating slugs. Each slugged
    object is also affiliated with a specific site object.
    """

    title = models.CharField(_("Title"), max_length=100)
    slug = models.CharField(_("URL"), max_length=100, blank=True, null=True)
    site = models.ForeignKey(Site, editable=False)

    objects = CurrentSiteManager()

    class Meta:
        abstract = True
        ordering = ("title", )

    def __unicode__(self):
        return self.title

    def save(self, update_site=False, *args, **kwargs):
        """
        Create a unique slug by appending an index. Set the site to
        the current site when the record is first created, unless the
        ``update_site`` argument is explicitly set to ``True``.
        """
        if not self.slug:
            # For custom content types, use the ``Page`` instance for
            # slug lookup.
            concrete_model = base_concrete_model(Slugged, self)
            self.slug = self.get_slug()
            i = 0
            while True:
                if i > 0:
                    if i > 1:
                        self.slug = self.slug.rsplit("-", 1)[0]
                    self.slug = "%s-%s" % (self.slug, i)
                qs = concrete_model.objects.all()
                if self.id is not None:
                    qs = qs.exclude(id=self.id)
                try:
                    qs.get(slug=self.slug)
                except ObjectDoesNotExist:
                    break
                i += 1
        if update_site or not self.id:
            self.site = Site.objects.get_current()
        super(Slugged, self).save(*args, **kwargs)

    def natural_key(self):
        return (self.slug, )

    def get_slug(self):
        """
        Allows subclasses to implement their own slug creation logic.
        """
        return slugify(self.title)
コード例 #29
0
ファイル: models.py プロジェクト: BramaBrama/spicy.core
class Settings(abs.BaseRedmineSettings):
    @staticmethod
    def get_robots_default():
        site = Site.objects.get_current()
        return ("# robots.txt for http://" + site.domain + "\n"
                "User-agent: *\n"
                "Host: " + site.domain + "\n"
                "Sitemap: http://" + site.domain + "/sitemap.xml")

    robots = models.TextField(max_length=3000,
                              blank=True,
                              verbose_name=_('robots.txt'),
                              default=lambda: Settings.get_robots_default())
    license_pub_key = models.CharField(_('User license public key'),
                                       max_length=255,
                                       blank=True)
    sentry_key = models.CharField(_('Sentry key'), max_length=255, blank=True)
    redmine_key = models.CharField(_('Redmine key'),
                                   max_length=255,
                                   blank=True)
    ga_key = models.CharField(_('Google Analytics API key'),
                              max_length=15,
                              blank=True)

    # developer mode
    # get developer settings from main server using API call and
    # licence_pub_key
    # ftp access data
    # manager_link

    enable_debug_toolbar = models.BooleanField(_('Enable DEBUG toolbar'),
                                               default=False)
    debug_mode = models.BooleanField(_('DEBUG mode'), default=False)
    admins_emails = models.TextField(_('Admins emails'), blank=True)
    managers_emails = models.TextField(_('Managers emails'), blank=True)

    #notify_50x
    #notify_404

    site = models.ForeignKey(Site,
                             verbose_name=_('Site'),
                             default=Site.objects.get_current,
                             unique=True)

    objects = models.Manager()
    on_site = CurrentSiteManager()

    def __unicode__(self):
        return unicode(_(u'Settings for {0}')).format(self.site.name)

    class Meta:
        permissions = (('change_managers_settings',
                        _('Can change managers settings')),
                       ('view_apps', _('View applications')))
        db_table = 'spicy_settings'
        abstract = False
コード例 #30
0
ファイル: models.py プロジェクト: revence27/rapidsms-script
class Script(models.Model):
    slug = models.SlugField(max_length=64, primary_key=True)
    name = models.CharField(max_length=128,
                            help_text="Human readable name.")
    sites = models.ManyToManyField(Site)
    objects = models.Manager()
    on_site = CurrentSiteManager('sites')
    enabled = models.BooleanField(default=True)
    def __unicode__(self):
        return "%s" % self.name