Exemplo n.º 1
0
class Courses(models.Model):
    level = (
        ('Micro', 'micro'),
        ('Foundation', 'foundation'),
        ('Advance', 'advance'),
    )

    title = models.CharField(max_length=70)
    slug = models.CharField(max_length=20)
    trainer = models.CharField(max_length=20)
    sme = models.CharField(max_length=20)
    level = models.CharField(max_length=10, choices=level)
    overview = models.TextField()
    content = models.TextField()
    image = models.ImageField(upload_to='photos/%Y/%m/%d', blank=True)
    small_image = models.ImageField(upload_to='photos/%Y/%m/%d', blank=True)
    duration = models.CharField(max_length=10)
    ongoing_batch = models.DateTimeField(auto_now=False)
    upcomming_batch = models.DateTimeField(auto_now=False)
    comments = CommentsField()
    rating = RatingField()

    def __unicode__(self):
        return self.title + ' ' + self.overview

    def get_absolute_url(self):
        return reverse('home', kwargs={})
Exemplo n.º 2
0
class Link(Displayable, Ownable):

    link = models.URLField(
        null=True, blank=(not getattr(settings, "LINK_REQUIRED", False)))
    rating = RatingField()
    comments = CommentsField()

    def get_absolute_url(self):
        return reverse("link_detail", kwargs={"slug": self.slug})

    @property
    def domain(self):
        return urlparse(self.url).netloc

    @property
    def url(self):
        if self.link:
            return self.link
        return current_request().build_absolute_uri(self.get_absolute_url())

    def save(self, *args, **kwargs):
        keywords = []
        if not self.keywords_string and getattr(settings, "AUTO_TAG", False):
            func_name = getattr(settings, "AUTO_TAG_FUNCTION",
                                "drum.links.utils.auto_tag")
            keywords = import_dotted_path(func_name)(self)
        super(Link, self).save(*args, **kwargs)
        if keywords:
            lookup = reduce(ior, [Q(title__iexact=k) for k in keywords])
            for keyword in Keyword.objects.filter(lookup):
                self.keywords.add(AssignedKeyword(keyword=keyword), bulk=False)
Exemplo n.º 3
0
class Juba(Displayable, Ownable):
    class Meta:
        verbose_name = _('聚吧')
        verbose_name_plural = _('聚吧')

    content = RichTextField(
        null=True, blank=(not getattr(settings, "JUBA_REQUIRED", False)))
    rating = RatingField()
    comments = CommentsField()

    def get_absolute_url(self):
        return reverse("juba_detail", kwargs={"slug": self.slug})

    @property
    def domain(self):
        return urlparse(self.url).netloc

    @property
    def url(self):
        if self.content:
            return self.content
        return current_request().build_absolute_uri(self.get_absolute_url())

    def save(self, *args, **kwargs):
        keywords = []
        self.slug = uuslug(self.title, instance=self)
        if not self.keywords_string and getattr(settings, "AUTO_TAG", False):
            keywords = self.title.rstrip(punctuation).split()
        super(Juba, self).save(*args, **kwargs)
        if keywords:
            lookup = reduce(ior, [Q(title__iexact=k) for k in keywords])
            for keyword in Keyword.objects.filter(lookup):
                self.keywords.add(AssignedKeyword(keyword=keyword))
Exemplo n.º 4
0
class BlogPost(Displayable, Ownable, RichText):
    """
    A blog post.
    """

    categories = models.ManyToManyField("BlogCategory",
                                        blank=True,
                                        related_name="blogposts")
    allow_comments = models.BooleanField(default=True)
    comments = CommentsField(verbose_name=_("Comments"))
    rating = RatingField(verbose_name=_("Rating"))
    featured_image = FileField(verbose_name=_("Featured Image"),
                               null=True,
                               upload_to="blog",
                               max_length=255,
                               blank=True)

    class Meta:
        verbose_name = _("Blog post")
        verbose_name_plural = _("Blog posts")
        ordering = ("-publish_date", )

    @models.permalink
    def get_absolute_url(self):
        url_name = "blog_post_detail"
        kwargs = {"slug": self.slug}
        if settings.BLOG_URLS_USE_DATE:
            url_name = "blog_post_detail_date"
            month = str(self.publish_date.month)
            if len(month) == 1:
                month = "0" + month
            kwargs.update({"month": month, "year": self.publish_date.year})
        return (url_name, (), kwargs)
Exemplo n.º 5
0
class Link(Displayable, Ownable):

    link = models.URLField(
        null=True, blank=(not getattr(settings, "LINK_REQUIRED", False)))
    rating = RatingField()
    comments = CommentsField()

    def get_absolute_url(self):
        return reverse("link_detail", kwargs={"slug": self.slug})

    @property
    def domain(self):
        return urlparse(self.url).netloc

    @property
    def url(self):
        if self.link:
            return self.link
        return current_request().build_absolute_uri(self.get_absolute_url())

    def save(self, *args, **kwargs):
        keywords = []
        if not self.keywords_string and getattr(settings, "AUTO_TAG", False):
            variations = lambda word: [
                word,
                sub("^([^A-Za-z0-9])*|([^A-Za-z0-9]|s)*$", "", word),
                sub("^([^A-Za-z0-9])*|([^A-Za-z0-9])*$", "", word)
            ]
            keywords = sum(map(variations, split("\s|/", self.title)), [])
        super(Link, self).save(*args, **kwargs)
        if keywords:
            lookup = reduce(ior, [Q(title__iexact=k) for k in keywords])
            for keyword in Keyword.objects.filter(lookup):
                self.keywords.add(AssignedKeyword(keyword=keyword))
Exemplo n.º 6
0
class BlogPost(Displayable, Ownable, RichText, AdminThumbMixin):
    """
    A blog post.
    """

    categories = models.ManyToManyField("BlogCategory",
                                        verbose_name=_("Categories"),
                                        blank=True,
                                        related_name="blogposts")
    allow_comments = models.BooleanField(verbose_name=_("Allow comments"),
                                         default=True)
    comments = CommentsField(verbose_name=_("Comments"))
    rating = RatingField(verbose_name=_("Rating"))
    featured_image = FileField(verbose_name=_("Featured Image"),
                               upload_to="blog",
                               format="Image",
                               max_length=255,
                               null=True,
                               blank=True)
    related_posts = models.ManyToManyField("self",
                                           verbose_name=_("Related posts"),
                                           blank=True)

    admin_thumb_field = "featured_image"

    class Meta:
        verbose_name = _("Blog post")
        verbose_name_plural = _("Blog posts")
        ordering = ("-publish_date", )

    @models.permalink
    def get_absolute_url(self):
        url_name = "blog_post_detail"
        kwargs = {"slug": self.slug}
        if settings.BLOG_URLS_USE_DATE:
            url_name = "blog_post_detail_date"
            month = str(self.publish_date.month)
            if len(month) == 1:
                month = "0" + month
            day = str(self.publish_date.day)
            if len(day) == 1:
                day = "0" + day
            kwargs.update({
                "day": day,
                "month": month,
                "year": self.publish_date.year,
            })
        return (url_name, (), kwargs)

    # These methods are wrappers for keyword and category access.
    # For Django 1.3, we manually assign keywords and categories
    # in the blog_post_list view, since we can't use Django 1.4's
    # prefetch_related method. Once we drop support for Django 1.3,
    # these can probably be removed.

    def category_list(self):
        return getattr(self, "_categories", self.categories.all())

    def keyword_list(self):
        return getattr(self, "_keywords", self.keywords.all())
class BlogPost(Displayable, Ownable, RichText, AdminThumbMixin):
    """
    A blog post.
    """

    categories = models.ManyToManyField(
        "BlogCategory",
        verbose_name=_("Categories"),
        blank=True,
        related_name="blogposts",
    )
    allow_comments = models.BooleanField(verbose_name=_("Allow comments"),
                                         default=True)
    comments = CommentsField(verbose_name=_("Comments"))
    rating = RatingField(verbose_name=_("Rating"))
    featured_image = FileField(
        verbose_name=_("Featured Image"),
        upload_to=upload_to("blog.BlogPost.featured_image", "blog"),
        format="Image",
        max_length=255,
        null=True,
        blank=True,
    )
    related_posts = models.ManyToManyField("self",
                                           verbose_name=_("Related posts"),
                                           blank=True)

    admin_thumb_field = "featured_image"

    class Meta:
        verbose_name = _("Blog post")
        verbose_name_plural = _("Blog posts")
        ordering = ("-publish_date", )

    def get_absolute_url(self):
        """
        URLs for blog posts can either be just their slug, or prefixed
        with a portion of the post's publish date, controlled by the
        setting ``BLOG_URLS_DATE_FORMAT``, which can contain the value
        ``year``, ``month``, or ``day``. Each of these maps to the name
        of the corresponding urlpattern, and if defined, we loop through
        each of these and build up the kwargs for the correct urlpattern.
        The order which we loop through them is important, since the
        order goes from least granular (just year) to most granular
        (year/month/day).
        """
        url_name = "blog_post_detail"
        kwargs = {"slug": self.slug}
        date_parts = ("year", "month", "day")
        if settings.BLOG_URLS_DATE_FORMAT in date_parts:
            url_name = "blog_post_detail_%s" % settings.BLOG_URLS_DATE_FORMAT
            for date_part in date_parts:
                date_value = str(getattr(self.publish_date, date_part))
                if len(date_value) == 1:
                    date_value = "0%s" % date_value
                kwargs[date_part] = date_value
                if date_part == settings.BLOG_URLS_DATE_FORMAT:
                    break
        return reverse(url_name, kwargs=kwargs)
Exemplo n.º 8
0
class Link(Displayable, Ownable):

    rating = RatingField()
    comments = CommentsField()
    link = models.URLField()

    @models.permalink
    def get_absolute_url(self):
        return ("link_detail", (), {"slug": self.slug})
Exemplo n.º 9
0
class Post(models.Model):

    #message = models.OneToOneField(Message)
    title = models.CharField(max_length=200)
    publish_date = models.DateTimeField(default=timezone.now())
    owner = models.ForeignKey('auth.User', related_name='posts')
    message = models.TextField()
    rating = RatingField()
    allow_comments = models.BooleanField(default=True)
    comments = CommentsField()
    related_posts = models.ManyToManyField("self", blank=True)
Exemplo n.º 10
0
class Link(Displayable, Ownable):

    link = models.URLField()
    rating = RatingField()
    comments = CommentsField()

    @models.permalink
    def get_absolute_url(self):
        return ("link_detail", (), {"slug": self.slug})

    def domain(self):
        return urlparse(self.link).netloc
Exemplo n.º 11
0
class Link(Displayable, Ownable):

    link = models.URLField(blank=True)
    rating = RatingField()
    comments = CommentsField()

    @models.permalink
    def get_absolute_url(self):
        return ("link_detail", (), {"pk": self.pk})

    @property
    def domain(self):
        return urlparse(self.link).netloc
Exemplo n.º 12
0
class Article(Displayable, Ownable, RichText, AdminThumbMixin):
    locations = models.ManyToManyField(Location, verbose_name=_("Locations"))
    is_topic = models.BooleanField(verbose_name=_("Is a topic?"), default=False)
    category_list = models.ManyToManyField(Category, verbose_name=_("Categories"),
                                           blank=False, null=False, related_name="articles")
    allow_comments = models.BooleanField(verbose_name=_("Allow comments"),
                                         default=True)
    comments = CommentsField(verbose_name=_("Comments"))
    featured_image = FileField(verbose_name=_("Featured Image"),
        format="Image", max_length=255, null=True, blank=True)

    author = models.ForeignKey("Author", related_name='articles')

    capsule_video = models.CharField(max_length=100, null=True, blank=True)

    featured_video = models.CharField(max_length=100, null=True, blank=True)

    featured_audio = models.CharField(max_length=100, null=True, blank=True)

    related_posts = models.ManyToManyField("self",
                                 verbose_name=_("Related Articles"), blank=True)
    types = models.ManyToManyField(Type, related_name="articles", verbose_name="Article Type")

    admin_thumb_field = "featured_image"

    objects = DisplayableManager()
    articles = ArticleManager()
    topics = TopicManager()

    class Meta:
        verbose_name = _("Article")
        verbose_name_plural = _("Articles")
        ordering = ("-publish_date",)
        app_label = "article"

    @models.permalink
    def get_absolute_url(self):
        name = "article-detail"
        if self.is_topic:
            name = "topic-detail"
        return (name, (), {"slug": self.slug})

    @property
    def is_video_article(self):
        return self.types.filter(title__iexact='Video').exists()

    @property
    def get_thumbnail(self):
        return self.featured_image
Exemplo n.º 13
0
class Link(Displayable, Ownable):
    c = (('hc', '清真餐厅'), ('yc', '一餐厅'), ('ec', '二餐厅'), ('sc', '三餐厅'),
         ('jby', '聚博园'), ('other', '未分类'))
    canteen = models.CharField(max_length=20, choices=c, default='ec')
    link = models.URLField(blank=True)  #这个根本不需要,不要删除吧,免得麻烦,只要不让它出现就行,完成
    rating = RatingField()
    comments = CommentsField()
    solved = models.BooleanField(default=False)

    @models.permalink
    def get_absolute_url(self):
        return ("link_detail", (), {"slug": self.slug})

    @property
    def domain(self):
        return urlparse(self.link).netloc
Exemplo n.º 14
0
class Link(Displayable, Ownable):
    link = models.URLField(
        null=True, blank=(not getattr(settings, "LINK_REQUIRED", False)))
    rating = RatingField()
    comments = CommentsField()
    audio_file = FileBrowseField(
        "Audio",
        max_length=200,
        extensions=[".mp3", ".mp4", ".wav", ".aiff", ".midi", ".m4p"],
        blank=True,
        null=True)

    def get_comments_number(self):
        comments = WaveSurfComment.objects.filter(object_pk=self.pk)
        return len(comments)

    get_comments_number.short_description = "Comments"

    comments_number = property(get_comments_number)

    def get_absolute_url(self):
        return reverse("link_detail", kwargs={"slug": self.slug})

    @property
    def domain(self):
        return urlparse(self.url).netloc

    @property
    def url(self):
        if self.link:
            return self.link
        return current_request().build_absolute_uri(self.get_absolute_url())

    def save(self, *args, **kwargs):
        keywords = []
        if not self.keywords_string and getattr(settings, "AUTO_TAG", False):
            variations = lambda word: [
                word,
                sub("^([^A-Za-z0-9])*|([^A-Za-z0-9]|s)*$", "", word),
                sub("^([^A-Za-z0-9])*|([^A-Za-z0-9])*$", "", word)
            ]
            keywords = sum(map(variations, split("\s|/", self.title)), [])
        super(Link, self).save(*args, **kwargs)
        if keywords:
            lookup = reduce(ior, [Q(title__iexact=k) for k in keywords])
            for keyword in Keyword.objects.filter(lookup):
                self.keywords.add(AssignedKeyword(keyword=keyword))
Exemplo n.º 15
0
class BlogPost(Displayable, Ownable, Content):
    """
    A blog post.
    """

    categories = models.ManyToManyField("BlogCategory", blank=True, 
                                        related_name="blogposts")
    comments = CommentsField(verbose_name=_("Comments"))

    class Meta:
        verbose_name = _("Blog post")
        verbose_name_plural = _("Blog posts")
        ordering = ("-publish_date",)

    @models.permalink
    def get_absolute_url(self):
        return ("blog_post_detail", (), {"slug": self.slug})
Exemplo n.º 16
0
class Link(Displayable, Ownable):
    link = models.URLField(null=True,
                           blank=(not getattr(settings, "LINK_REQUIRED", False)))
    rating = RatingField()
    comments = CommentsField()
    main_image = CharField(_("Product Image"), help_text=_(
        "We try to load an image automatically. You can also set one yourself. E.g. http://example.com/image.png"),
                           max_length=256, null=True, blank=True)
    new_price = DecimalField(_("New Price"), help_text=_(
        "Optional field. The new price of the product."), max_digits=7, decimal_places=2, null=True, blank=True)
    old_price = DecimalField(_("Old Price"), help_text=_(
        "Optional field. The old or regular price of the product."),
                             max_digits=7, decimal_places=2, null=True, blank=True)
    is_expired = BooleanField(_("Expired"), help_text=_("Indicates if the deal conditions still apply"), default=False)
    deal_expiry_date = DateTimeField(_("Expires at"), help_text=_("Optional field. The deal expires at this date"),
                                     null=True, blank=True)

    objects = LinkManager()

    def get_absolute_url(self):
        return reverse("link_detail", kwargs={"slug": self.slug})

    @property
    def domain(self):
        return urlparse(self.url).netloc

    @property
    def url(self):
        if self.link:
            return self.link
        return current_request().build_absolute_uri(self.get_absolute_url())

    def save(self, *args, **kwargs):
        keywords = []
        if not self.keywords_string and getattr(settings, "AUTO_TAG", False):
            variations = lambda word: [word,
                                       sub("^([^A-Za-z0-9])*|([^A-Za-z0-9]|s)*$", "", word),
                                       sub("^([^A-Za-z0-9])*|([^A-Za-z0-9])*$", "", word)]
            keywords = sum(map(variations, split("\s|/", self.title)), [])
        super(Link, self).save(*args, **kwargs)
        if keywords:
            lookup = reduce(ior, [Q(title__iexact=k) for k in keywords])
            for keyword in Keyword.objects.filter(lookup):
                self.keywords.add(AssignedKeyword(keyword=keyword))
Exemplo n.º 17
0
class Event(models.Model):
    level = (
        ('Micro', 'micro'),
        ('Foundation', 'foundation'),
        ('Advance', 'advance'),
    )
    title = models.CharField(max_length=70)
    couponcode = models.CharField(max_length=10)
    slug = models.CharField(max_length=20)
    trainer = models.CharField(max_length=20)
    sme = models.CharField(max_length=20)
    level = models.CharField(max_length=10, choices=level)
    overview = models.TextField()
    content = models.TextField()
    image = models.ImageField(upload_to='photos/%Y/%m/%d', blank=True)
    duration = models.CharField(max_length=10)
    comments = CommentsField()
    participants = models.IntegerField()

    def __unicode__(self):
        return self.title + ' ' + self.overview
Exemplo n.º 18
0
class ForumPost(Displayable, Ownable, RichText):
    """
    A Forum post
    """
    categories = models.ManyToManyField(BlogCategory,
                                        verbose_name=_("Categories"),
                                        blank=True,
                                        related_name="forumposts")
    comments = CommentsField(verbose_name=_("Comments"))
    rating = RatingField(verbose_name=_("Rating"))

    class Meta:
        verbose_name = _("Forum post")
        verbose_name_plural = _("Forum posts")

    def get_absolute_url(self):
        """
        URLs for blog posts can either be just their slug, or prefixed
        with a portion of the post's publish date, controlled by the
        setting ``BLOG_URLS_DATE_FORMAT``, which can contain the value
        ``year``, ``month``, or ``day``. Each of these maps to the name
        of the corresponding urlpattern, and if defined, we loop through
        each of these and build up the kwargs for the correct urlpattern.
        The order which we loop through them is important, since the
        order goes from least granualr (just year) to most granular
        (year/month/day).
        """
        url_name = "forum_post_detail"
        kwargs = {"slug": self.slug}
        date_parts = ("year", "month", "day")
        if settings.BLOG_URLS_DATE_FORMAT in date_parts:
            url_name = "blog_post_detail_%s" % settings.BLOG_URLS_DATE_FORMAT
            for date_part in date_parts:
                date_value = str(getattr(self.publish_date, date_part))
                if len(date_value) == 1:
                    date_value = "0%s" % date_value
                kwargs[date_part] = date_value
                if date_part == settings.BLOG_URLS_DATE_FORMAT:
                    break
        return reverse(url_name, kwargs=kwargs)
Exemplo n.º 19
0
class EventPost(Displayable, Ownable, RichText, AdminThumbMixin):
    """
    A event post.
    """

    dini = models.DateTimeField(_("Departure"), null=True, blank=True)
    dfin = models.DateTimeField(_("Arrival"), null=True, blank=True)
    map = models.CharField(_("Map"), max_length=500, null=True, blank=True)
    price = models.IntegerField(_("Price"), null=True, blank=True)

    categories = models.ManyToManyField("EventCategory",
                                        verbose_name=_("Categories"),
                                        blank=True,
                                        related_name="eventposts")
    allow_comments = models.BooleanField(verbose_name=_("Allow comments"),
                                         default=False)
    comments = CommentsField(verbose_name=_("Comments"))
    rating = RatingField(verbose_name=_("Rating"))
    featured_image = FileField(verbose_name=_("Featured Image"),
                               upload_to=upload_to(
                                   "event.EventPost.featured_image", "event"),
                               format="Image",
                               max_length=255,
                               null=True,
                               blank=True)
    related_posts = models.ManyToManyField("self",
                                           verbose_name=_("Related posts"),
                                           blank=True)

    admin_thumb_field = "featured_image"
    """
    Fields for data's event.
    """
    class Meta:
        verbose_name = _("Event post")
        verbose_name_plural = _("Event posts")
        ordering = ("-publish_date", )

    @models.permalink
    def get_absolute_url(self):
        url_name = "event_post_detail"
        kwargs = {"slug": self.slug}
        if settings.EVENT_URLS_USE_DATE:
            url_name = "event_post_detail_date"
            month = str(self.publish_date.month)
            if len(month) == 1:
                month = "0" + month
            day = str(self.publish_date.day)
            if len(day) == 1:
                day = "0" + day
            kwargs.update({
                "day": day,
                "month": month,
                "year": self.publish_date.year,
            })
        return (url_name, (), kwargs)

    # These methods are deprecated wrappers for keyword and category
    # access. They existed to support Django 1.3 with prefetch_related
    # not existing, which was therefore manually implemented in the
    # event list views. All this is gone now, but the access methods
    # still exist for older templates.

    def category_list(self):
        from warnings import warn
        warn("event_post.category_list in templates is deprecated"
             "use event_post.categories.all which are prefetched")
        return getattr(self, "_categories", self.categories.all())

    def keyword_list(self):
        from warnings import warn
        warn("event_post.keyword_list in templates is deprecated"
             "use the keywords_for template tag, as keywords are prefetched")
        try:
            return self._keywords
        except AttributeError:
            keywords = [k.keyword for k in self.keywords.all()]
            setattr(self, "_keywords", keywords)
            return self._keywords
Exemplo n.º 20
0
class Event(Displayable, Ownable, RichText, AdminThumbMixin):
    """
    A event.
    """

    start = models.DateTimeField(_("Start"))
    end = models.DateTimeField(_("End"), blank=True, null=True)
    location = models.ForeignKey("EventLocation", blank=True, null=True)
    facebook_event = models.BigIntegerField(_('Facebook'), blank=True, null=True) #
    allow_comments = models.BooleanField(verbose_name=_("Allow comments"),
                                         default=True)
    comments = CommentsField(verbose_name=_("Comments"))
    rating = RatingField(verbose_name=_("Rating"))
    featured_image = FileField(verbose_name=_("Featured Image"),
        upload_to=upload_to("mezzanine_agenda.Event.featured_image", "event"),
        format="Image", max_length=255, null=True, blank=True)

    admin_thumb_field = "featured_image"

    class Meta:
        verbose_name = _("Event")
        verbose_name_plural = _("Events")
        ordering = ("-start",)

    def clean(self):
        """
        Validate end date is after the start date.
        """
        super(Event, self).clean()

        if self.end and self.start > self.end:
            raise ValidationError("Start must be sooner than end.")

    def get_absolute_url(self):
        """
        URLs for events can either be just their slug, or prefixed
        with a portion of the post's publish date, controlled by the
        setting ``EVENT_URLS_DATE_FORMAT``, which can contain the value
        ``year``, ``month``, or ``day``. Each of these maps to the name
        of the corresponding urlpattern, and if defined, we loop through
        each of these and build up the kwargs for the correct urlpattern.
        The order which we loop through them is important, since the
        order goes from least granualr (just year) to most granular
        (year/month/day).
        """
        url_name = "event_detail"
        kwargs = {"slug": self.slug}
        date_parts = ("year", "month", "day")
        if settings.EVENT_URLS_DATE_FORMAT in date_parts:
            url_name = "event_detail_%s" % settings.EVENT_URLS_DATE_FORMAT
            for date_part in date_parts:
                date_value = str(getattr(self.publish_date, date_part))
                if len(date_value) == 1:
                    date_value = "0%s" % date_value
                kwargs[date_part] = date_value
                if date_part == settings.EVENT_URLS_DATE_FORMAT:
                    break
        return reverse(url_name, kwargs=kwargs)

    def get_icalendar_event(self):
        """
        Builds an icalendar.event object from event data.
        """
        icalendar_event = IEvent()
        icalendar_event.add('summary'.encode("utf-8"), self.title)
        icalendar_event.add('url', 'http://{domain}{url}'.format(
            domain=Site.objects.get(id=current_site_id()).domain,
            url=self.get_absolute_url(),
        ))
        if self.location:
            icalendar_event.add('location'.encode("utf-8"), self.location.address)
        icalendar_event.add('dtstamp', self.start)
        icalendar_event.add('dtstart', self.start)
        if self.end:
            icalendar_event.add('dtend', self.end)
        icalendar_event['uid'.encode("utf-8")] = "event-{id}@{domain}".format(
            id=self.id,
            domain=Site.objects.get(id=current_site_id()).domain,
        ).encode("utf-8")
        return icalendar_event
Exemplo n.º 21
0
class IyphPost(Displayable, Ownable, RichText, AdminThumbMixin):
    """
    A Iyph  post.
    """

    categories = models.ManyToManyField("IyphCategory",
                                        verbose_name=_("Categories"),
                                        blank=True,
                                        related_name="iyphposts")
    allow_comments = models.BooleanField(verbose_name=_("Allow comments"),
                                         default=True)
    comments = CommentsField(verbose_name=_("Comments"))
    rating = RatingField(verbose_name=_("Rating"))
    featured_image = FileField(verbose_name=_("Featured Image"),
                               upload_to=upload_to(
                                   "iyph.IyphPost.featured_image", "iyph"),
                               format="Image",
                               max_length=255,
                               null=True,
                               blank=True)
    related_posts = models.ManyToManyField("self",
                                           verbose_name=_("Related posts"),
                                           blank=True)

    admin_thumb_field = "featured_image"

    class Meta:
        verbose_name = _("Iyph")
        verbose_name_plural = _("Iyph")
        ordering = ("-publish_date", )

    #@models.permalink
    def get_absolute_url(self):
        """
        URLs for iyph posts can either be just their slug, or prefixed
        with a portion of the post's publish date, controlled by the
        setting ``Iyph_URLS_DATE_FORMAT``, which can contain the value
        ``year``, ``month``, or ``day``. Each of these maps to the name
        of the corresponding urlpattern, and if defined, we loop through
        each of these and build up the kwargs for the correct urlpattern.
        The order which we loop through them is important, since the
        order goes from least granualr (just year) to most granular
        (year/month/day).
        """
        url_name = "iyph_post_detail"
        kwargs = {"slug": self.slug}
        date_parts = ("year", "month", "day")
        if settings.IYPH_URLS_DATE_FORMAT in date_parts:
            url_name = "iyph_post_detail_%s" % settings.IYPH_URLS_DATE_FORMAT
            for date_part in date_parts:
                date_value = str(getattr(self.publish_date, date_part))
                if len(date_value) == 1:
                    date_value = "0%s" % date_value
                kwargs[date_part] = date_value
                if date_part == settings.IYPH_URLS_DATE_FORMAT:
                    break
        return (url_name, (), kwargs)

    # These methods are deprecated wrappers for keyword and category
    # access. They existed to support Django 1.3 with prefetch_related
    # not existing, which was therefore manually implemented in the
    # iyph list views. All this is gone now, but the access methods
    # still exist for older templates.

    def category_list(self):
        from warnings import warn
        warn("iyph_post.category_list in templates is deprecated"
             "use iyph_post.categories.all which are prefetched")
        return getattr(self, "_categories", self.categories.all())

    def keyword_list(self):
        from warnings import warn
        warn("iyph_post.keyword_list in templates is deprecated"
             "use the keywords_for template tag, as keywords are prefetched")
        try:
            return self._keywords
        except AttributeError:
            keywords = [k.keyword for k in self.keywords.all()]
            setattr(self, "_keywords", keywords)
            return self._keywords
Exemplo n.º 22
0
class Event(Displayable, SubTitle, Ownable, RichText, AdminThumbMixin):
    """
    An event.
    """

    parent = models.ForeignKey('Event',
                               verbose_name=_('parent'),
                               related_name='children',
                               blank=True,
                               null=True,
                               on_delete=models.SET_NULL)
    category = models.ForeignKey('EventCategory',
                                 verbose_name=_('category'),
                                 related_name='events',
                                 blank=True,
                                 null=True,
                                 on_delete=models.SET_NULL)

    start = models.DateTimeField(_("Start"))
    end = models.DateTimeField(_("End"), blank=True, null=True)
    date_text = models.CharField(_('Date text'),
                                 max_length=512,
                                 blank=True,
                                 null=True)

    location = models.ForeignKey("EventLocation",
                                 blank=True,
                                 null=True,
                                 on_delete=models.SET_NULL)
    facebook_event = models.BigIntegerField(_('Facebook ID'),
                                            blank=True,
                                            null=True)
    shop = models.ForeignKey('EventShop',
                             verbose_name=_('shop'),
                             related_name='events',
                             blank=True,
                             null=True,
                             on_delete=models.SET_NULL)
    external_id = models.IntegerField(_('External ID'), null=True, blank=True)
    is_full = models.BooleanField(verbose_name=_("Is Full"), default=False)

    brochure = FileField(_('brochure'),
                         upload_to='brochures',
                         max_length=1024,
                         blank=True)
    prices = models.ManyToManyField('EventPrice',
                                    verbose_name=_('prices'),
                                    related_name='events',
                                    blank=True)
    no_price_comments = RichTextField(_('Price comments'),
                                      blank=True,
                                      null=True)
    mentions = models.TextField(_('mentions'), blank=True)

    allow_comments = models.BooleanField(verbose_name=_("Allow comments"),
                                         default=False)
    comments = CommentsField(verbose_name=_("Comments"))
    rating = RatingField(verbose_name=_("Rating"))
    rank = models.IntegerField(verbose_name=_('rank'), blank=True, null=True)

    admin_thumb_field = "photo"

    class Meta:
        verbose_name = _("Event")
        verbose_name_plural = _("Events")
        ordering = (
            "rank",
            "start",
        )

    def clean(self):
        """
        Validate end date is after the start date.
        """
        super(Event, self).clean()

        if self.end and self.start > self.end:
            raise ValidationError("Start must be sooner than end.")

    def save(self, *args, **kwargs):
        super(Event, self).save(*args, **kwargs)
        # take some values from parent
        if not self.parent is None:
            self.title = self.parent.title
            self.user = self.parent.user
            self.status = self.parent.status
            if not self.location:
                self.location = self.parent.location
            if not self.description:
                self.description = self.parent.description
                self.description_en = self.parent.description_en
            if not self.category:
                self.category = self.parent.category
            if not self.mentions:
                self.mentions = self.parent.mentions
                self.mentions_en = self.parent.mentions_en
            parent_images = self.parent.images.select_related('event').all()
            for parent_image in parent_images:
                if not self.images.filter(file=parent_image.file,
                                          type=parent_image.type):
                    parent_image.pk = None
                    parent_image.save()
                    parent_image.event = self
                    parent_image.save()
            if not self.user:
                self.user = self.parent.user
            if not self.status:
                self.status = self.parent.status
            if not self.content:
                self.content = self.parent.content
                self.content_en = self.parent.content_en
            if not self.departments.all():
                parent_departments = self.parent.departments.all()
                for parent_department in parent_departments:
                    parent_department.pk = None
                    parent_department.save()
                    parent_department.event = self
                    parent_department.save()
            if not self.links.all():
                all_links = self.parent.links.all()
                for link in all_links:
                    link.pk = None
                    link.save()
                    link.event = self
                    link.save()
        super(Event, self).save(*args, **kwargs)

    def update(self, *args, **kwargs):
        super(Event, self).save(*args, **kwargs)

    def get_absolute_url(self):
        """
        URLs for events can either be just their slug, or prefixed
        with a portion of the post's publish date, controlled by the
        setting ``EVENT_URLS_DATE_FORMAT``, which can contain the value
        ``year``, ``month``, or ``day``. Each of these maps to the name
        of the corresponding urlpattern, and if defined, we loop through
        each of these and build up the kwargs for the correct urlpattern.
        The order which we loop through them is important, since the
        order goes from least granualr (just year) to most granular
        (year/month/day).
        """
        url_name = "event_detail"
        kwargs = {"slug": self.slug}
        date_parts = ("year", "month", "day")
        if settings.EVENT_URLS_DATE_FORMAT in date_parts:
            url_name = "event_detail_%s" % settings.EVENT_URLS_DATE_FORMAT
            for date_part in date_parts:
                date_value = str(getattr(self.publish_date, date_part))
                if len(date_value) == 1:
                    date_value = "0%s" % date_value
                kwargs[date_part] = date_value
                if date_part == settings.EVENT_URLS_DATE_FORMAT:
                    break
        return reverse(url_name, kwargs=kwargs)

    def get_icalendar_event(self):
        """
        Builds an icalendar.event object from event data.
        """
        icalendar_event = IEvent()
        icalendar_event.add('summary'.encode("utf-8"), self.title)
        icalendar_event.add(
            'url', 'http://{domain}{url}'.format(
                domain=Site.objects.get(id=current_site_id()).domain,
                url=self.get_absolute_url(),
            ))
        if self.location:
            icalendar_event.add('location'.encode("utf-8"),
                                self.location.address)
        icalendar_event.add('dtstamp', self.start)
        icalendar_event.add('dtstart', self.start)
        if self.end:
            icalendar_event.add('dtend', self.end)
        icalendar_event['uid'.encode("utf-8")] = "event-{id}@{domain}".format(
            id=self.id,
            domain=Site.objects.get(id=current_site_id()).domain,
        ).encode("utf-8")
        return icalendar_event

    def _get_next_or_previous_by_start_date(self, is_next, **kwargs):
        """
        Retrieves next or previous object by start date. We implement
        our own version instead of Django's so we can hook into the
        published manager and concrete subclasses.
        """
        arg = "start__gt" if is_next else "start__lt"
        order = "start" if is_next else "-start"
        lookup = {arg: self.start}
        concrete_model = base_concrete_model(Displayable, self)
        try:
            queryset = concrete_model.objects.published
        except AttributeError:
            queryset = concrete_model.objects.all
        try:
            return queryset(**kwargs).filter(**lookup).filter(
                parent__isnull=True).order_by(order)[0]
        except IndexError:
            pass

    def get_next_by_start_date(self, **kwargs):
        """
        Retrieves next object by start date.
        """
        return self._get_next_or_previous_by_start_date(True, **kwargs)

    def get_previous_by_start_date(self, **kwargs):
        """
        Retrieves previous object by start date.
        """
        return self._get_next_or_previous_by_start_date(False, **kwargs)

    def date_format(self):
        if self.periods.all():
            return 'D j F'
        else:
            return 'l j F'
Exemplo n.º 23
0
class WikiPage(Displayable, Ownable):
    """
    A wiki page.
    """

    content = WikiTextField(_("Content"))
    categories = models.ManyToManyField("WikiCategory",
                                        verbose_name=_("Categories"),
                                        blank=True,
                                        related_name="wikipages")
    allow_comments = models.BooleanField(verbose_name=_("Allow comments"),
                                         default=True)
    comments = CommentsField(verbose_name=_("Comments"))
    rating = RatingField(verbose_name=_("Rating"))
    featured_image = FileField(verbose_name=_("Featured Image"),
                               null=True,
                               upload_to="wiki",
                               max_length=255,
                               blank=True)

    search_fields = ("content", )

    objects = DisplayableManager()

    class Meta:
        verbose_name = _("Wiki page")
        verbose_name_plural = _("Wiki pages")
        ordering = ("title", )
        permissions = WIKIPAGE_PERMISSIONS

    def can_view_wikipage(self, user):
        # Everyone.
        return True

    def can_edit_wikipage(self, user):
        # Simple cases first, we don't want to waste CPU and DB hits.

        # Everyone.
        if (settings.WIKI_PRIVACY == wiki_settings.WIKI_PRIVACY_OPENED):
            return True

        # Registered users.
        elif (settings.WIKI_PRIVACY == wiki_settings.WIKI_PRIVACY_REGISTERED
              ) and (user.is_authenticated()):
            return True

        # TODO: Checks done by guardian for owner and admins.
        #elif 'view_wikipage' in get_perms(user, self):
        elif (settings.WIKI_PRIVACY == wiki_settings.WIKI_PRIVACY_MODERATED
              ) and (user.has_perm('mezzanine_wiki.change_wikipage')):
            return True

        # Owner.
        elif self.user == user:
            return True

        # Fallback to closed page.
        return False

    def get_absolute_url(self):
        return reverse("wiki_page_detail", kwargs={"slug": self.slug})
Exemplo n.º 24
0
class Lesson(Page, RichText):
    overview = RichTextField('Lesson Overview')
    duration = models.CharField('Duration',
                                help_text='Duration of lesson',
                                max_length=255,
                                blank=True,
                                null=True)
    week = models.IntegerField(
        'Week',
        help_text=
        'Week within the unit (only use for first lesson of the week)',
        blank=True,
        null=True)
    pacing_weight = models.DecimalField(
        'Pacing Weight',
        help_text='Higher numbers take up more space pacing calendar',
        default=1,
        max_digits=4,
        decimal_places=1,
        blank=True,
        null=True)
    unplugged = models.BooleanField(default=False)
    resources = SortedManyToManyField(Resource, blank=True)
    prep = RichTextField('Preparation',
                         help_text='ToDos for the teacher to prep this lesson',
                         blank=True,
                         null=True)
    questions = RichTextField(
        'Support Details',
        help_text='Open questions or comments about this lesson',
        blank=True,
        null=True)
    cs_content = RichTextField(
        'Purpose',
        help_text='Purpose of this lesson in progression and CS in general',
        blank=True,
        null=True)
    ancestor = models.ForeignKey('self', blank=True, null=True)
    standards = models.ManyToManyField(Standard, blank=True)
    anchor_standards = models.ManyToManyField(
        Standard,
        help_text='1 - 3 key standards this lesson focuses on',
        related_name="anchors",
        blank=True)
    vocab = models.ManyToManyField(Vocab, blank=True)
    blocks = models.ManyToManyField(Block, blank=True)
    comments = CommentsField()
    unit = models.ForeignKey(curricula.models.Unit, blank=True, null=True)
    curriculum = models.ForeignKey(curricula.models.Curriculum,
                                   blank=True,
                                   null=True)
    number = models.IntegerField('Number', blank=True, null=True)
    image = models.ImageField('Image', blank=True, null=True)
    stage = JSONField('Code Studio stage', blank=True, null=True)
    _old_slug = models.CharField('old_slug',
                                 max_length=2000,
                                 blank=True,
                                 null=True)

    class Meta:
        ordering = ["number"]

    def __unicode__(self):
        return self.title

    def __deepcopy(self):
        lesson_copy = self
        lesson_copy.pk = None
        # deepcopy page, activities, prereqs, and objectives
        lesson_copy.save()
        return lesson_copy

    def can_move(self, request, new_parent):
        parent_type = getattr(new_parent, 'content_model', None)
        if not (parent_type == 'lesson' or parent_type == 'chapter'
                or parent_type == 'unit'):
            print "no unit here"
            msg = 'Lesson cannot live under a %s' % parent_type
            raise PageMoveException(msg)

    def get_absolute_url(self):
        # Check if this is the child of a lesson, and therefore optional
        if hasattr(self.parent, 'lesson'):
            return "%soptional/%s/" % (self.parent.lesson.get_absolute_url(),
                                       str(self.number))
        try:
            return "%s%s/" % (self.unit.get_absolute_url(), str(self.number))
        except AttributeError:
            return "%s%s/" % (self.get_unit().get_absolute_url(),
                              str(self.number))

    def get_overview_url(self):
        return '%soverview/' % self.get_absolute_url()

    def get_unit(self):
        parent = self.parent
        while not parent.content_model == 'unit':
            parent = parent.parent
            if parent is None:
                return None
        return parent.unit

    def get_number(self):
        order = 1
        if self.parent.content_model == 'chapter':
            chapter = self.parent.chapter
            while chapter is not None:
                try:
                    chapter = chapter.get_previous_by_order()
                    if hasattr(chapter, "chapter"):
                        chapter = chapter.chapter
                        order += chapter.lessons.count()
                except AttributeError as e:
                    chapter = None

        if self._order is not None:
            try:
                order += int(self._order)
            except Exception as e:
                print(e)

        return order

    def get_curriculum(self):
        return self.get_unit().curriculum

    def get_levels(self):
        if self.stage:
            raw_levels = self.stage.get('levels')

            levels = []  # To store levels organized by logical chunk
            counter = 0
            last_type = raw_levels[0].get('named_level')
            last_progression = raw_levels[0].get('progression')
            levels.insert(counter, {
                'named': last_type,
                'progression': last_progression,
                'levels': []
            })

            for level in raw_levels:

                current_type = level.get('named_level')
                current_progression = level.get('progression')
                if last_type != current_type or last_progression != current_progression:
                    last_type = current_type
                    last_progression = current_progression
                    counter += 1
                    levels.insert(
                        counter, {
                            'named': last_type,
                            'progression': last_progression,
                            'levels': []
                        })

                levels[counter]['levels'].append(level)

            return levels
        else:
            return

    def get_levels_from_levelbuilder(self):
        try:
            url = "https://levelbuilder-studio.code.org/s/%s/stage/%d/summary_for_lesson_plans" % (
                self.unit.stage_name, self.number)
            response = urllib2.urlopen(url)
            data = json.loads(response.read())
            self.stage = data
            self.save()
        except Exception:
            logger.warning("Couldn't get stage details for %s" % self)

    # Return publishable urls for JackFrost
    def jackfrost_urls(self):
        urls = [self.get_absolute_url(), self.get_overview_url()]
        return urls

    def jackfrost_can_build(self):
        try:
            can_build = settings.ENABLE_PUBLISH and self.status == 2 and not self.login_required and \
                        not self.unit.login_required and not self.curriculum.login_required
        except:
            can_build = False

        return can_build

    def publish(self, children=False):
        if self.jackfrost_can_build():
            for url in self.jackfrost_urls():
                try:
                    read, written = build_single(url)
                    slack_message(
                        'slack/message.slack', {
                            'message':
                            'published %s %s' %
                            (self.content_model, self.title),
                            'color':
                            '#00adbc'
                        })
                    yield json.dumps(written)
                    yield '\n'
                except Exception, e:
                    yield json.dumps(e.message)
                    yield '\n'
                    logger.exception('Failed to publish %s' % url)
        else:
Exemplo n.º 25
0
class ForumPost(Displayable, Ownable, RichText, AdminThumbMixin):
    """
    A forum post.
    """
    categories = models.ManyToManyField("ForumCategory",
                                        verbose_name=_("Categories"),
                                        blank=True, related_name="forumposts")
    
    
    allow_comments = models.BooleanField(verbose_name=_("Forum discussion OPEN for comments (to CLOSE the discussion un-check this)."),
                                         default=True)
    comments = CommentsField(verbose_name=_("Comments"))
    rating = RatingField(verbose_name=_("Rating"))
    featured_image = FileField(verbose_name=_("Featured Image"),
        upload_to=upload_to("forum.ForumPost.featured_image", "forum"),
        format="Image", max_length=255, null=True, blank=True)
    related_posts = models.ManyToManyField("self",
                                 verbose_name=_("Related posts"), blank=True)
    
    admin_thumb_field = "featured_image"
    
    users = models.ManyToManyField(User,
        verbose_name=_("Users this forum post is accessible to"),
        related_name='forumusers', blank=True)#, null=True)    
    groups = models.ManyToManyField(Group,
        verbose_name=_("Groups this forum post is accessible to"),
        related_name='forumgroups', blank=True)#, null=True)
    notification_groups = models.ManyToManyField(Group,
        verbose_name=_("Groups you want automatically notify of new POST and Comments"),
        related_name='forumnotificationgroups', blank=True)#, null=True)    
    login_required = models.BooleanField(verbose_name=_("Login required"),
                                         default=True)
    

    class Meta:
        verbose_name = _("Forum post")
        verbose_name_plural = _("Forum posts")
        ordering = ("-publish_date",)
        # south overrides syncdb, so the following perms are not created
        # unless we are starting the project from scratch.
        # solution: python manage.py syncdb --all
        # or
        # manage.py datamigration myapp add_perm_foo --freeze=contenttypes --freeze=auth
        # http://stackoverflow.com/questions/1742021/adding-new-custom-permissions-in-django
        permissions = ( 
            ("can_view", "View Forum Post"),
        )

    #@models.permalink
    def get_absolute_url(self):
        """
        URLs for forum posts can either be just their slug, or prefixed
        with a portion of the post's publish date, controlled by the
        setting ``FORUM_URLS_DATE_FORMAT``, which can contain the value
        ``year``, ``month``, or ``day``. Each of these maps to the name
        of the corresponding urlpattern, and if defined, we loop through
        each of these and build up the kwargs for the correct urlpattern.
        The order which we loop through them is important, since the
        order goes from least granualr (just year) to most granular
        (year/month/day).
        """
        url_name = "forum_post_detail"
        kwargs = {"slug": self.slug}
        date_parts = ("year", "month", "day")
        if settings.FORUM_URLS_DATE_FORMAT in date_parts:
            url_name = "forum_post_detail_%s" % settings.FORUM_URLS_DATE_FORMAT
            for date_part in date_parts:
                date_value = str(getattr(self.publish_date, date_part))
                if len(date_value) == 1:
                    date_value = "0%s" % date_value
                kwargs[date_part] = date_value
                if date_part == settings.FORUM_URLS_DATE_FORMAT:
                    break
        #return (url_name, (), kwargs)

        return reverse(url_name, kwargs=kwargs)

    # These methods are deprecated wrappers for keyword and category
    # access. They existed to support Django 1.3 with prefetch_related
    # not existing, which was therefore manually implemented in the
    # forum list views. All this is gone now, but the access methods
    # still exist for older templates.

    def category_list(self):
        from warnings import warn
        warn("forum_post.category_list in templates is deprecated"
             "use forum_post.categories.all which are prefetched")
        return getattr(self, "_categories", self.categories.all())

    def keyword_list(self):
        from warnings import warn
        warn("forum_post.keyword_list in templates is deprecated"
             "use the keywords_for template tag, as keywords are prefetched")
        try:
            return self._keywords
        except AttributeError:
            keywords = [k.keyword for k in self.keywords.all()]
            setattr(self, "_keywords", keywords)
            return self._keywords
Exemplo n.º 26
0
class Recommend(Displayable, Ownable, RichText, AdminThumbMixin):
    #khong can dung doan nay do Displayable cua Mezzanine da co san
    #title =     models.CharField(max_length=250, blank= True, null= True)
    #R_publish = models.DateTimeField(default=timezone.now)
    #created = models.DateTimeField(auto_now_add=True)
    #updated = models.DateTimeField(auto_now=True)
    #R_status =  models.CharField(max_length=10,
    #                          choices=STATUS_CHOICES,
    #                          default='draft')
    #objects = models.Manager()  # The default manager.
    #published = PublishedManager()  # The Dahl-specific manager.
    Stock_chosen = models.ManyToManyField(Estimate,
                                          through='Update_Trade',
                                          verbose_name="Chọn CP",
                                          blank=True,
                                          related_name="Recommend")
    Streng = models.IntegerField(
        "Độ mạnh",
        null=True,
        blank=True,
        validators=[MaxValueValidator(100),
                    MinValueValidator(0)],
        help_text='0-100')
    #Judgement = models.TextField("Đề xuất GD", max_length=2000, blank=True, null=True)
    @staticmethod
    def sohoa(a):
        So = int(a)
        if So >= 80:
            Do_manh = "RẤT MẠNH"
        elif So >= 70:
            Do_manh = "MẠNH"
        elif So >= 60:
            Do_manh = "KHÁ MẠNH"
        elif So >= 40:
            Do_manh = "TRUNG BÌNH"
        elif So >= 30:
            Do_manh = "YẾU"

        else:
            Do_manh = "RẤT YẾU"
        return Do_manh

    def do_manh(self):
        return self.sohoa(self.Streng)

    categories = models.ManyToManyField("Recommend_Category",
                                        blank=True,
                                        related_name="Recommends")
    allow_comments = models.BooleanField(verbose_name="Allow comments",
                                         default=True)
    comments = CommentsField(verbose_name="Còn bạn nhận định thế nào về TT ?")
    rating = RatingField(verbose_name="Rating")
    related_posts = models.ManyToManyField("self",
                                           verbose_name=_("Related posts"),
                                           blank=True)
    viewed = models.IntegerField(default=0)

    def get_absolute_url(self):
        """
        URLs for blog posts can either be just their slug, or prefixed
        with a portion of the post's publish date, controlled by the
        setting ``BLOG_URLS_DATE_FORMAT``, which can contain the value
        ``year``, ``month``, or ``day``. Each of these maps to the name
        of the corresponding urlpattern, and if defined, we loop through
        each of these and build up the kwargs for the correct urlpattern.
        The order which we loop through them is important, since the
        order goes from least granular (just year) to most granular
        (year/month/day).
        """
        url_name = "nhandinhthitruong:daily"
        kwargs = {"slug": self.slug}
        date_parts = ("year", "month", "day")
        if settings.BLOG_URLS_DATE_FORMAT in date_parts:
            url_name = "nhandinhthitruong:daily_%s" % settings.BLOG_URLS_DATE_FORMAT
            for date_part in date_parts:
                date_value = str(getattr(self.publish_date, date_part))
                if len(date_value) == 1:
                    date_value = "0%s" % date_value
                kwargs[date_part] = date_value
                if date_part == settings.BLOG_URLS_DATE_FORMAT:
                    break
        return reverse(url_name, kwargs=kwargs)

    class Meta:
        verbose_name = "Recommend"
        verbose_name_plural = "Recommends"
        ordering = ('-publish_date', )

    def __str__(self):
        return self.title
Exemplo n.º 27
0
class AdvCourses(models.Model):
    title = models.CharField(max_length=70)
    comments = CommentsField()

    def __unicode__(self):
        return self.title