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 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)
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))
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))
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={})
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)
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)
class Product(Displayable, Priced, RichText, AdminThumbMixin): """ Container model for a product that stores information common to all of its variations such as the product's title and description. """ available = models.BooleanField(_("Available for purchase"), default=False) image = CharField(_("Image"), max_length=100, blank=True, null=True) categories = models.ManyToManyField("Category", blank=True, verbose_name=_("Product categories")) date_added = models.DateTimeField(_("Date added"), auto_now_add=True, null=True) related_products = models.ManyToManyField( "self", verbose_name=_("Related products"), blank=True) upsell_products = models.ManyToManyField("self", verbose_name=_("Upsell products"), blank=True) rating = RatingField(verbose_name=_("Rating")) objects = DisplayableManager() admin_thumb_field = "image" search_fields = {"variations__sku": 100} class Meta: verbose_name = _("Product") verbose_name_plural = _("Products") unique_together = ("sku", "site") def save(self, *args, **kwargs): """ Copies the price fields to the default variation when ``SHOP_USE_VARIATIONS`` is False, and the product is updated via the admin change list. """ updating = self.id is not None super(Product, self).save(*args, **kwargs) if updating and not settings.SHOP_USE_VARIATIONS: default = self.variations.get(default=True) self.copy_price_fields_to(default) @models.permalink def get_absolute_url(self): return ("shop_product", (), {"slug": self.slug}) def copy_default_variation(self): """ Copies the price and image fields from the default variation when the product is updated via the change view. """ default = self.variations.get(default=True) default.copy_price_fields_to(self) if default.image: self.image = default.image.file.name self.save()
class Link(Displayable, Ownable): rating = RatingField() comments = CommentsField() link = models.URLField() @models.permalink def get_absolute_url(self): return ("link_detail", (), {"slug": self.slug})
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)
class Path(Displayable, Ownable, RichText, AdminThumbMixin): startNode = models.ForeignKey("Node", verbose_name=u"路径起点", related_name="pathstart", blank=True) endNode = models.ForeignKey("Node", verbose_name=u"路径终点", related_name="pathend", blank=True) pathLength = models.DecimalField(max_digits=6, decimal_places=2, verbose_name=u"时间长度", blank=True) rating = RatingField(verbose_name=_("Rating")) featuredImage = FileField(verbose_name=_("Featured Image"), upload_to=upload_to( "learnTopology.Path.featuredImage", "blog"), format="Image", max_length=255, null=True, blank=True) admin_thumb_field = "featuredImage" class Meta: verbose_name = u"路径" verbose_name_plural = u"路径" ordering = ("id", ) def all_direct_previous_paths(self): pnodes = self.startNode.all_direct_previous_nodes() for pnode in pnodes: ppaths = Path.objects.filter(startNode=pnode, endNode=self.startNode) if len(ppaths) == 0: yield None else: yield ppaths[0] def all_next_paths(self): e = self.endNode e0 = e.nextNode while e and e0: nps = Path.objects.filter(startNode=e, endNode=e0) if len(nps) == 0: yield None else: yield nps[0] e = e0 e0 = e.nextNode def get_absolute_url(self): return "%s?s=%d&e=%d" % (reverse("learn_path_detail"), self.startNode.id, self.endNode.id)
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
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
class Product(Displayable, Priced, RichText): """ Container model for a product that stores information common to all of its variations such as the product's title and description. """ available = models.BooleanField(_("Available for purchase"), default=False) image = CharField(max_length=100, blank=True, null=True) categories = models.ManyToManyField("Category", blank=True, related_name="products") date_added = models.DateTimeField(_("Date added"), auto_now_add=True, null=True) related_products = models.ManyToManyField("self", blank=True) upsell_products = models.ManyToManyField("self", blank=True) rating = RatingField(verbose_name=_("Rating")) objects = DisplayableManager() class Meta: verbose_name = _("Product") verbose_name_plural = _("Products") @models.permalink def get_absolute_url(self): return ("shop_product", (), {"slug": self.slug}) def copy_default_variation(self): """ Copies the price and image fields from the default variation. """ default = self.variations.get(default=True) for field in Priced._meta.fields: if not isinstance(field, models.AutoField): setattr(self, field.name, getattr(default, field.name)) if default.image: self.image = default.image.file.name self.save() def admin_thumb(self): if self.image is None: return "" from mezzanine.core.templatetags.mezzanine_tags import thumbnail thumb_url = thumbnail(self.image, 24, 24) return "<img src='%s%s' />" % (settings.MEDIA_URL, thumb_url) admin_thumb.allow_tags = True admin_thumb.short_description = ""
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
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))
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))
class BlogPost(Displayable, Ownable, RichText): """ A blog post. """ categories = models.ManyToManyField("BlogCategory", blank=True, related_name="blogposts") comments = CommentsField(verbose_name=_("Comments")) rating = RatingField(verbose_name=_("Rating")) 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})
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)
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
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
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
class ThreadedComment(ExportModelOperationsMixin('threadedcomment'), Comment): """ Extend the ``Comment`` model from ``django_comments`` to add comment threading. ``Comment`` provides its own site foreign key, so we can't inherit from ``SiteRelated`` in ``mezzanine.core``, and therefore need to set the site on ``save``. ``CommentManager`` inherits from Mezzanine's ``CurrentSiteManager``, so everything else site related is already provided. """ by_author = models.BooleanField(_("By the blog author"), default=False) replied_to = models.ForeignKey("self", null=True, editable=False, related_name="comments") rating = RatingField(verbose_name=_("Rating")) objects = CommentManager() class Meta: verbose_name = _("Comment") verbose_name_plural = _("Comments") def get_absolute_url(self): """ Use the URL for the comment's content object, with a URL hash appended that references the individual comment. """ url = self.content_object.get_absolute_url() return "%s#comment-%s" % (url, self.id) def save(self, *args, **kwargs): """ Set the current site ID, and ``is_public`` based on the setting ``COMMENTS_DEFAULT_APPROVED``. """ if not self.id: self.is_public = settings.COMMENTS_DEFAULT_APPROVED self.site_id = current_site_id() super(ThreadedComment, self).save(*args, **kwargs) ################################ # Admin listing column methods # ################################ def intro(self): return truncatewords_html(self.comment, 20) intro.short_description = _("Comment") def avatar_link(self): from mezzanine.core.templatetags.mezzanine_tags import gravatar_url vars = (self.user_email, gravatar_url(self.email), self.user_name) return ("<a href='mailto:%s'><img style='vertical-align:middle; " "margin-right:3px;' src='%s' />%s</a>" % vars) avatar_link.allow_tags = True avatar_link.short_description = _("User") def admin_link(self): return "<a href='%s'>%s</a>" % (self.get_absolute_url(), ugettext("View on site")) admin_link.allow_tags = True admin_link.short_description = "" # Exists for backward compatibility when the gravatar_url template # tag which took the email address hash instead of the email address. @property def email_hash(self): return self.email
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'
class Product(BaseProduct, Priced, RichText, AdminThumbMixin): """ Container model for a product that stores information common to all of its variations such as the product's title and description. """ manufacturer = CharField(_("Производитель"), editable=True, blank=True, null=True, max_length=4, default=None, choices=MANUFACTURERS) content_model = models.CharField(_("Тип товара"), editable=False, max_length=50, null=True) available = models.BooleanField(_("Available for purchase"), default=True) image = CharField(_("Image"), max_length=100, blank=True, null=True) categories = models.ManyToManyField("Category", blank=False, verbose_name=_("Product categories")) date_added = models.DateTimeField(_("Date added"), auto_now_add=True, null=True) related_products = models.ManyToManyField( "self", verbose_name=_("Related products"), blank=True) upsell_products = models.ManyToManyField("self", verbose_name=_("Upsell products"), blank=True) rating = RatingField(verbose_name=_("Rating")) admin_thumb_field = "image" search_fields = {"variations__sku": 100} class Meta: verbose_name = _("Product") verbose_name_plural = _("Products") @classmethod def get_content_models(cls): """ Return all ``Product`` subclasses. """ is_product_subclass = lambda cls: issubclass(cls, Product) cmp = lambda a, b: (int(b is Product) - int(a is Product) or a._meta. verbose_name < b._meta.verbose_name) return sorted(filter(is_product_subclass, models.get_models()), cmp) def get_content_model(self): """ Provides a generic method of retrieving the instance of the custom product's model, if there is one. """ return getattr(self, self.content_model, None) def save(self, *args, **kwargs): """ Copies the price fields to the default variation when ``SHOP_USE_VARIATIONS`` is False, and the product is updated via the admin change list. """ if self.id is None: self.content_model = self._meta.object_name.lower() updating = self.id is not None super(Product, self).save(*args, **kwargs) if updating and not settings.SHOP_USE_VARIATIONS: default = self.variations.get(default=True) self.copy_price_fields_to(default) @models.permalink def get_absolute_url(self): return ("shop_product", (), {"slug": self.slug}) def copy_default_variation(self): """ Copies the price and image fields from the default variation when the product is updated via the change view. """ default = self.variations.get(default=True) default.copy_price_fields_to(self) if default.image: self.image = default.image.file.name self.save()
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})
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
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
class Product(Displayable, Priced, RichText, AdminThumbMixin): """ Container model for a product that stores information common to all of its variations such as the product's title and description. """ seller_id = models.IntegerField(blank=True, null=True) available = models.BooleanField(_("Available for purchase"), default=False) image = CharField(_("Image"), max_length=100, blank=True, null=True) categories = models.ManyToManyField("Category", blank=True, verbose_name=_("Product categories")) date_added = models.DateTimeField(_("Date added"), auto_now_add=True, null=True) related_products = models.ManyToManyField( "self", verbose_name=_("Related products"), blank=True) upsell_products = models.ManyToManyField("self", verbose_name=_("Upsell products"), blank=True) rating = RatingField(verbose_name=_("Rating")) objects = DisplayableManager() admin_thumb_field = "image" class Meta: verbose_name = _("Product") verbose_name_plural = _("Products") def setup(self, request): """ Set order fields that are stored in the session, item_total and total based on the given cart, and copy the cart items to the order. Called in the final step of the checkout process prior to the payment handler being called. """ self.seller_id = request.user.id def save(self, *args, **kwargs): """ Copies the price fields to the default variation when ``SHOP_USE_VARIATIONS`` is False, and the product is updated via the admin change list. """ updating = self.id is not None super(Product, self).save(*args, **kwargs) if updating and not settings.SHOP_USE_VARIATIONS: default = self.variations.get(default=True) self.copy_price_fields_to(default) @models.permalink def get_absolute_url(self): return ("shop_product", (), {"slug": self.slug}) def copy_default_variation(self): """ Copies the price and image fields from the default variation when the product is updated via the change view. """ default = self.variations.get(default=True) default.copy_price_fields_to(self) if default.image: self.image = default.image.file.name self.save()
class WaveSurfComment(Comment): start = models.FloatField(default=0) end = models.FloatField(default=0) objects = Comment.objects rating = RatingField(verbose_name="Rating")