Ejemplo n.º 1
0
class Comment(models.Model):
    """
    Stores comments for different content types
    """
    class Meta:
        query = 'comments.models.CommentQuerySet'

    owner = models.ForeignKey(related_name="comments", delete_cascade=True)
    author = models.AnyField(null=True, blank=True, default=None)
    created = models.DateTimeField(default=get_utc_now, blank=True)
    body = models.TextField()

    def get_created_as_timezone(self, tz):
        try:
            created = self['created'].astimezone(timezone(tz))
        except:
            created = self['created']
        return created

    def get_content(self):
        return mark_safe(self['body'])

    def get_comments(self):
        return Comment.query().filter(owner=self)

    def get_author(self):
        if isinstance(
                self['author'],
                dict) and 'pk' in self['author'] and 'class' in self['author']:
            return self['author']['class'].query().get(pk=self['author']['pk'])

        return self['author']
Ejemplo n.º 2
0
class Answer(models.Model):
    question = models.ForeignKey(Question,
                                 related_name="answers",
                                 delete_cascade=True)
    author = models.AnyField(null=True, blank=True, default=None)
    parent_answer = models.ForeignKey('self',
                                      null=True,
                                      blank=True,
                                      related_name='children_answers',
                                      delete_cascade=True)
    text = models.TextField()
    modified_date = models.DateTimeField(blank=True,
                                         default=datetime.datetime.now,
                                         db_index=True)

    def __unicode__(self):
        return self['text']

    def get_author(self):
        if isinstance(
                self['author'],
                dict) and 'pk' in self['author'] and 'class' in self['author']:
            try:
                return self['author']['class'].query().get(
                    pk=self['author']['pk'])
            except ObjectDoesNotExist:
                return None

        return self['author']
Ejemplo n.º 3
0
class Image(models.Model):
    """
    Image model to store images
    """
    class Meta:
        query = 'images.models.ImageQuerySet'
        ordering = ('-created', )

    name = models.CharField(max_length=100)
    is_active = models.BooleanField(default=True, db_index=True, blank=True)
    #    is_public = models.BooleanField(default=True, db_index=True, blank=True)
    keywords = models.ListField(blank=True, null=True)
    alt_text = models.CharField(max_length=100, blank=True, null=True)
    copyright = models.CharField(max_length=100, blank=True)
    title = models.TextField(blank=True)
    image_center = models.CharField(max_length=20, blank=True)
    existing_thumbnails = models.TextField(blank=True)
    image = models.ImageField()
    sites = models.ManyToManyField(Site, blank=True, related_name='images')
    created = models.DateTimeField(default=datetime.datetime.now, blank=True)

    __getattr__ = thumbs_getattr('image')

    def get_image_center_for_200(self):
        if not self['image_center'] or not self['image']:
            return ''
        center = map(int, self['image_center'].split(','))
        factor = (min(200.0, self['image'].height, self['image'].width) /
                  max([self['image'].height, self['image'].width]))
        return '%s,%s' % (center[0] * factor, center[1] * factor)

    def __unicode__(self):
        return self['name']

    def all_sites(self):
        return Site.query()
Ejemplo n.º 4
0
class Post(models.Model):
    class Meta:
        query = 'articles.models.PostQuerySet'
        ordering = ('-date', )
        permissions = tuple(('can_post_to_%s' % site_name[0],
                             'User can post to site %s' % site_name[1])
                            for site_name in SITES)

    name = models.CharField(max_length=255)
    author = models.ForeignKey('auth.User', blank=False, null=False)
    slug = models.SlugField(max_length=255, blank=True)
    source = models.TextField()
    text = models.TextField()
    teaser = models.TextField()
    is_draft = models.BooleanField(blank=True, null=False, default=True)
    created_date = models.DateTimeField(blank=True,
                                        null=False,
                                        default=datetime.now)
    date = models.DateTimeField(blank=True,
                                null=False,
                                verbose_name='Updated Date')
    site = models.ForeignKey(Site, related_name='posts')

    def get_categories(self):
        return ",".join(pc['category']['name'] for pc in self['categories'])

    def get_url(self):
        return reverse("post_view", kwargs={'slug': self['slug']})

    def __unicode__(self):
        return self['name']

    def save(self, **kwargs):
        # TODO: slug field should be unique with site/articles
        if not self.get('slug', False):
            self['slug'] = slugify(self['name'])

        source = self.get('source', None)
        source = image_compiler.render(source) or source
        if source is not None:
            self['text'] = markdown2.markdown(source)
        self['date'] = datetime.now()

        return super(Post, self).save(**kwargs)

    def get_content(self):
        return mark_safe(self['text'])

    def get_teaser(self):
        return mark_safe(self['teaser'])

    def get_previous_post(self, collection_name):
        if not hasattr(self, '_previous_post'):
            posts = Post.query().filter(
                site=self['site'],
                is_draft=False,
                created_date__lt=self['created_date']).order_by(
                    '-created_date').by_collection(collection_name)
            try:
                self._previous_post = posts[0]
            except IndexError:
                self._previous_post = None

        return self._previous_post

    def get_next_post(self, collection_name):
        if not hasattr(self, '_next_post'):
            posts = Post.query().filter(
                site=self['site'],
                is_draft=False,
                created_date__gt=self['created_date']).order_by(
                    'created_date').by_collection(collection_name)
            try:
                self._next_post = posts[0]
            except IndexError:
                self._next_post = None

        return self._next_post
Ejemplo n.º 5
0
class Page(models.Model):
    class Meta:
        query = 'pages.models.PageQuerySet'
        ordering = ('-last_update', )

    RENDER_TYPE_RAW = 'raw'
    RENDER_TYPE_MARKDOWN = 'markdown'
    RENDER_TYPE_CHOICES = (
        (RENDER_TYPE_RAW, 'Raw HTML'),
        (RENDER_TYPE_MARKDOWN, 'Markdown'),
    )

    name = models.CharField(max_length=255)
    author = models.ForeignKey('auth.User',
                               blank=False,
                               null=False,
                               related_name='pages')
    slug = models.SlugField(max_length=255,
                            blank=True,
                            null=False,
                            allow_slashes=True)
    #    real_slug = models.SlugField(max_length=255, blank=True, null=False, allow_slashes=True)
    title = models.CharField(max_length=255)
    #    position = models.SmallIntegerField(blank=True, null=False,
    #            help_text='Menu position (for ranking of menu items)')
    text = models.TextField()
    source = models.TextField()
    last_update = models.DateTimeField(blank=False, null=False)
    site = models.ForeignKey(Site, related_name='pages')
    template_name = models.CharField(max_length=100, blank=True)
    markup = models.CharField(max_length=20,
                              blank=True,
                              choices=RENDER_TYPE_CHOICES,
                              default=RENDER_TYPE_RAW)
    keywords = models.ListField(null=True, blank=True)
    is_published = models.BooleanField(default=True, db_index=True, blank=True)
    is_home = models.BooleanField(default=False, blank=True)
    parent_page = models.ForeignKey("self",
                                    blank=True,
                                    default=None,
                                    related_name="children_pages")

    #    use_parent_page_in_url = models.BooleanField(default=False, blank=True, verbose_name="Show middle pages in url")

    def __unicode__(self):
        return self['name']

    def _save_text_from_source(self, source_field_name, text_field_name):
        source = self.get(source_field_name, None)
        if self['markup'] == self.RENDER_TYPE_MARKDOWN:
            self[text_field_name] = markdown2.markdown(source or '')
        else:
            self[text_field_name] = source or ''

    def save(self, **kwargs):
        self['last_update'] = datetime.now()
        self._save_text_from_source('source', 'text')
        page_model_save.send(instance=self)

        return super(Page, self).save(**kwargs)

    def publish(self):
        self['is_published'] = True
        self.save()

    def get_children(self):
        return Page.query().filter(parent_page=self)

    def get_name(self, lang='default'):
        name = page_get_name.send(instance=self, lang=lang)
        if not len(name) or not name[0]:
            name = self['name']
        else:
            name = name[0]
        return name

    def get_title(self, lang='default'):
        title = page_get_title.send(instance=self, lang=lang)
        if not len(title) or not title[0]:
            title = self['title']
        else:
            title = title[0]
        return title

    def get_url(self):
        kwargs = {}
        collections = Collection.query().filter(site=self['site'],
                                                items__contains=str(
                                                    self['pk']))
        if collections.count():
            kwargs = collections[0].get_slugs(
            )  # TODO: what to do if page belongs to more than 1 collection?
        kwargs['slug'] = self['slug']

        try:
            from routes import dynamic_url_patterns
            url_patterns = dynamic_url_patterns[self['site']['name']] if self[
                'site']['name'] in dynamic_url_patterns else []
        except ImportError:
            url_patterns = []

        try:
            return reverse('pages_views_category_view',
                           kwargs=kwargs,
                           dynamic_url_patterns=url_patterns)
        except:
            return '/%s/' % self['slug']

#    def get_url(self):
#        if self['is_home']:
#            return reverse("page_view_home")
#
#        parent = self['parent_page']
#        slug = self['slug']
#        while parent and self['use_parent_page_in_url']:
#            slug = "%s/%s" % (parent['slug'], slug)
#            parent = parent['parent_page']
#        return reverse("page_view", kwargs={'slug': slug})

    def get_content(self, lang='default'):
        regex = re.compile("\{(IMAGE|COLLECTION|ALL|FORM):(.*?)\}")
        content = page_get_content.send(instance=self, lang=lang, regex=regex)
        if not len(content) or not content[0]:
            content = mark_safe(regex.sub('', self['text']))
        else:
            content = content[0]
        return content