class MyBlog(models.Model): title = models.CharField(max_length=255) body = MarkdownxField() #body = RichTextField(verbose_name="default") tags = models.ManyToManyField(Tag) author = models.ForeignKey(User, null=True) publishing_date = models.DateTimeField(auto_now_add=True) slug = models.SlugField() rating = RatingField(can_change_vote=True) genre = models.IntegerField(choices=GENRE_CHOICES, default=0) ref_title1 = models.CharField(max_length=255, default=' ', blank=True) ref_url1 = models.URLField(blank=True, null=True) ref_title2 = models.CharField(max_length=255, default=' ', blank=True) ref_url2 = models.URLField(blank=True, null=True) ref_title3 = models.CharField(max_length=255, default=' ', blank=True) ref_url3 = models.URLField(blank=True, null=True) ref_title4 = models.CharField(max_length=255, default=' ', blank=True) ref_url4 = models.URLField(blank=True, null=True) ref_title5 = models.CharField(max_length=255, default=' ', blank=True) ref_url5 = models.URLField(blank=True, null=True) def __str__(self): return self.title
class Topic(models.Model): SCOPE_CHOICES = [ (u'local', u'Local'), (u'national', u'National'), (u'worldwide', u'Worldwide'), ] title = models.CharField(max_length=512) article_link = models.TextField(validators=[URLValidator()]) created_by = models.ForeignKey(CustomUser) created_on = models.DateTimeField(auto_now_add=True) rating = RatingField(can_change_vote=True) tags = TaggableManager() image = models.ImageField(upload_to='static', max_length=512, blank=True, null=True) image_url = models.URLField(max_length=512) scope = models.CharField( choices=SCOPE_CHOICES, max_length=9, ) address = AddressField(null=True) def __str__(self): return str(self.title)
class Ipost(models.Model): #replies message = models.TextField(max_length=4000) ##<the matter of reply topic = models.ForeignKey( Topic) ##<the @see Topic for which this is a reply created_at = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(User, on_delete=models.CASCADE) rating = RatingField( can_change_vote=True ) ##< sores number upvotes, downvotes; 1 for each UPVOTE and -1 for each DOWNVOTE def __str__(self): return self.message
class Thread(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) rating = RatingField(can_change_vote=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('thread-detail', kwargs={'pk': self.pk})
class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='post_comments') text = models.TextField() rating = RatingField(can_change_vote=True) created = models.DateTimeField(default=timezone.now) def __str__(self): return self.text[:10] def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.post.id})
class Problem(models.Model): prob_stat = models.TextField() created = models.DateField(default=date.today) college = models.ForeignKey(College, related_name='collegename', null=True, blank=True, on_delete=models.CASCADE) rating = RatingField(can_change_vote=True, blank=True, null=True) count = models.IntegerField() booltrue = models.BooleanField(default=False) def __str__(self): return self.prob_stat
class Votable(models.Model): updown = RatingField(can_change_vote=True) class Meta: abstract = True def get_does_user_already_vote(self, user): content_type = ContentType.objects.get_for_model(self.__class__) vote = Vote.objects.filter(user=user, object_id=self.id, content_type=content_type) does_user_already_vote = True if vote.exists() and vote[0].score > 0 else False return does_user_already_vote def set_does_user_already_vote(self, user): self.does_user_already_vote = self.get_does_user_already_vote(user) return self
class DefaultResource(models.Model): # # This class is the parent class for all resources in the media manager # objects = InheritanceManager() title = models.CharField(max_length=100) created_date = models.DateTimeField(auto_now_add=True, auto_now=False) edited_date = models.DateTimeField(auto_now_add=False, auto_now=True) level = models.ManyToManyField(AssoeLevel, db_index=True) agebracket = models.ManyToManyField(AgeBracket, db_index=True) pathway = models.ManyToManyField(AssoePathway, db_index=True) tags = TaggableManager() slug = models.SlugField(max_length=100, editable=False, blank=True) updownvotes = RatingField(can_change_vote=True) views = models.DecimalField(max_digits=20, decimal_places=2, default=0, blank=True) score = models.DecimalField(max_digits=20, decimal_places=4, default=0, blank=True) icon = models.CharField(max_length=254, editable=False, blank=True) subject = models.ManyToManyField(AssoeSubjects, db_index=True) description = models.TextField(blank=True) def calculate_score(self): score = float(self.updownvotes.likes) - float( self.updownvotes.dislikes) score = score + (float(self.views)**(float(1) / float(2))) self.score = score rounded_score = int(round(self.score)) if rounded_score < -1: return -1 else: return rounded_score def __unicode__(self): return self.title def save(self, *args, **kwargs): self.calculate_score() if not self.id: self.slug = slugify(self.title) super(DefaultResource, self).save(*args, **kwargs)
class Project(models.Model): user = models.ForeignKey(User) name = models.CharField(max_length=200) slug = models.SlugField(max_length=200, unique=True) description = models.TextField() problem = models.TextField(null=True, blank=True) rating = RatingField(can_change_vote=True) tags = TagField() image = models.ImageField(upload_to="images") public_views = models.IntegerField(default=0) private_views = models.IntegerField(default=0) funding = models.DecimalField(max_digits=15, decimal_places=2, default=0) goal = models.DecimalField(max_digits=15, decimal_places=2, default=0) paypal = models.EmailField(blank=True) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) def __unicode__(self): return self.name
class Food(models.Model): title = models.CharField(max_length=128, verbose_name='标题') description = models.TextField(verbose_name='描述') cover_image = models.ImageField(upload_to='foods/cover/%Y/%m/%d', verbose_name='封面图片') rating = RatingField(can_change_vote=True) users_wta = models.ManyToManyField(User, related_name='foods_wta', blank=True, verbose_name='想吃的用户') users_ate = models.ManyToManyField(User, related_name='foods_ate', blank=True, verbose_name='吃过的用户') link = models.URLField(blank=True, verbose_name='相关链接') category = models.ForeignKey(FoodCategory, related_name='foods', verbose_name='分类') user = models.ForeignKey(User, related_name='foods_shared', verbose_name='创建用户') created = models.DateTimeField(auto_now_add=True, verbose_name='添加日期') tags = TaggableManager(blank=True, help_text='多个标签以逗号分隔', verbose_name="标签") @classmethod def get_food_categorys(self): return FoodCategory.objects.all() def get_absolute_url(self): return reverse('food:detail', kwargs={'food_id': self.id}) def __str__(self): return self.title class Meta: verbose_name = '食品' verbose_name_plural = '食品' ordering = ('-created', )
class SubscriberArticle(ArticleBase): rating = RatingField(can_change_vote=True) is_suscriber_article = True @staticmethod def top_articles(): desde = datetime.now() - timedelta(days=15) return SubscriberArticle.objects.get_query_set().filter( date_published__gt=desde)[:3] def __unicode__(self): return self.headline + ' ( por ' + str(self.created_by) + ' )' def save(self, *args, **kwargs): self.type = self.COMUNIDAD if not self.slug: self.slug = slugify(self.headline) super(SubscriberArticle, self).save(*args, **kwargs) @models.permalink def get_absolute_url(self): return ('comunidad_article_detail', (), {'slug': self.slug})
class Question(models.Model): class Meta: ordering = ['-date_updated'] user = models.ForeignKey(User, related_name="questions") # completedTODO: get user working^ question = models.TextField(blank=False, null=False) # unique=True, question_html = models.TextField(blank=False, null=False) answer = models.TextField(blank=False, null=False) answer_html = models.TextField(blank=False, null=False) date_created = models.DateTimeField(auto_now=True, null=True) date_updated = models.DateTimeField(auto_now=True, null=True) slug = models.SlugField(unique=True, default='') tags = TaggableManager() # TODO: create up vote system rating = RatingField(can_change_vote=True) # TODO: create replies to comments system def __str__(self): return self.question # ^ to display an object in the Django admin site and # as the value inserted into a template when it displays an object. def save(self, *args, **kwargs): self.question_html = misaka.html(self.question) self.answer_html = misaka.html(self.answer) super().save(*args, **kwargs) def get_absolute_url(self): return reverse("questions:detail", kwargs={ "slug": self.slug, "pk": self.pk, "username": self.user.username, })
class RatingTestModel(models.Model): rating = RatingField(can_change_vote=True) rating2 = RatingField(can_change_vote=False) def __unicode__(self): return unicode(self.pk)
class Post(models.Model): title = models.CharField(max_length=200) rating = RatingField(can_change_vote=True) def __str__(self): return self.title
class Post(TimeStampedModel, ContentTypeModel): id = models.BigAutoField(primary_key=True) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(_('Title'), max_length=200) slug = models.SlugField(_('Slug'), max_length=200, unique=True) description = MartorField(_('Description')) tags = models.ManyToManyField('Tag') keywords = models.CharField(_('Keywords'), null=True, blank=True, max_length=200, help_text=_('Separate by comma (,)')) meta_description = models.TextField(_('Meta Description'), null=True, blank=True) is_featured = models.BooleanField(_('Is Featured?'), default=False) publish = models.BooleanField(_('Publish'), default=True) rating = RatingField(can_change_vote=True) objects = PostManager() def __str__(self): return self.title def get_absolute_url(self): return reverse('apps.blog:post_detail', kwargs={'slug': self.slug}) def get_content_type(self): """ function to get the content_type object for this model """ self.content_type = super().get_content_type() return self.content_type def get_visitors(self): """ function to get the queryset of visitors """ if hasattr(self, 'content_type'): content_type = self.content_type else: content_type = self.get_content_type() queries = {'content_type': content_type, 'object_id': self.id} return Visitor.objects.published().filter(**queries) @property def total_visitors(self): """ count the total of visitors """ return self.get_visitors().count() def get_favorites(self): """ function to get the queryset of favorites """ if hasattr(self, 'content_type'): content_type = self.content_type else: content_type = self.get_content_type() queries = {'content_type': content_type, 'object_id': self.id} return Favorite.objects.published().filter(**queries) @property def total_favorites(self): """ count the total of favorites """ return self.get_favorites().count() def delete(self, *args, **kwargs): """ run delete action for instanced objects """ queries = {'content_type__model': 'post', 'object_id': self.id} Favorite.objects.filter(**queries).delete() Visitor.objects.filter(**queries).delete() Vote.objects.filter(**queries).delete() super().delete(*args, **kwargs) class Meta: verbose_name = _('Post') verbose_name_plural = _('Posts') ordering = ('-created_at', )
return self.category.name + " | " + self.text def firebase_user_id(self): return UserProfile.objects.get(user__id=self.user_id).legacy_id or 0 def comment_user_avatar(self): return UserProfile.objects.get(user__id=self.user_id).image or "" def user_voted(self): content_type = ContentType.objects.get_for_model(self.__class__) try: voted = Vote.objects.get(object_id=self.id, content_type=content_type, user=User.objects.get(id=self.user_id), vote=1) return True except Exception, e: return False Comment.add_to_class('firebase_user_id', firebase_user_id) Comment.add_to_class('rating', RatingField(can_change_vote=True)) Comment.add_to_class('avatar', comment_user_avatar) Comment.add_to_class('user_voted', user_voted)
class Ad(models.Model): category = models.ForeignKey(Category, blank=True, null=True) user = models.ForeignKey(User, default=1) created_on = models.DateTimeField( default=timezone.now) #change to timezone sensitive expires_on = models.DateTimeField(blank=True, null=True) address = models.CharField(max_length=255, default="", blank=True, null=True) position = GeopositionField(blank=True, null=True) location = models.PointField( null=True, blank=True, ) advertiseId = models.CharField(max_length=255, default="", blank=True, null=True) categoryId = models.CharField(max_length=255, default="", blank=True, null=True) chinese = models.BooleanField(default=False) language = models.CharField(max_length=7, choices=LANGUAGES, default="en") coupon = models.CharField(max_length=255, default="", blank=True, null=True) descendingTime = models.FloatField(default=-time.time()) description = HTMLField(default=" ") descriptionPlainText = models.TextField(default=" ", blank=True, null=True) enableEmail = models.BooleanField(default=False) enablePhone = models.BooleanField(default=False) favoriteCount = models.IntegerField(default=0) views = models.IntegerField(default=0) feature = models.NullBooleanField(default=False, blank=True, null=True) flagCount = models.IntegerField(default=0) hidden = models.BooleanField(default=False) legacy_id = models.TextField(max_length=255, default="", blank=True, null=True) isChinese = models.NullBooleanField(default=False, blank=True, null=True) isFeatured = models.NullBooleanField(default=False, blank=True, null=True) isHtmlDes = models.BooleanField(default=True) isStandout = models.BooleanField(default=False) name = models.CharField(max_length=255, default="") price = models.DecimalField(max_digits=20, decimal_places=2, default=0, blank=True, null=True) saleOff = models.CharField(max_length=255, blank=True, null=True) shareCount = models.IntegerField(default=0) standout = models.NullBooleanField(default=False, blank=True, null=True) createdAt = models.FloatField(default=time.time()) updatedAt = models.FloatField(default=time.time()) userId = models.CharField(max_length=255, default="HZETmXH25SXNDWVc4ZtNaR07Ru13") Referral_ID = models.CharField(max_length=255, blank=True, null=True) rating = RatingField(can_change_vote=True) # tags # video = models.URLField(default="", null=True, blank=True, max_length=256) # def get_absolute_url(self): # return "https://console.firebase.google.com/project/sosokan-1452b/database/data/advertises/" + str(self.legacy_id) def get_absolute_url(self): return "/ad/" + str(self.id) def __unicode__(self): return self.name def expired(self): if self.expires_on <= datetime.datetime.now(): return True else: return False @property def imageHeader(self): try: reduce_by = float(self.adimage.first().width) / 300 return { "url": self.adimage.first().header.url, "width": "300", "height": int(round(self.adimage.first().height / reduce_by)) } except: return None @property def short_description(self): if self.descriptionPlainText: cleanr = re.compile('<.*?>') r_unwanted = re.compile("[\n\t\r]") stripped = r_unwanted.sub("", self.descriptionPlainText) cleantext = re.sub(cleanr, '', stripped)[:80] return cleantext else: return "" @property def defualt_image(self): if self.isChinese: try: category = self.category return category.iconChinese except AttributeError: return "" else: try: category = self.category return category.iconEnglish except AttributeError: return "" def save(self, *args, **kwargs): if self.created_on is None: if not self.language: self.language = (self.isChinese or self.chinese) and "zh-hans" or "en" self.created_on = datetime.datetime.now() super(Ad, self).save(*args, **kwargs) class Meta: ordering = ['-created_on'] @property def comments(self): instance = self content_type = ContentType.objects.get_for_model(instance.__class__) obj_id = instance.id qs = Comment.objects.filter(content_type=content_type, object_pk=obj_id) return qs def image_tag(self): if self.imageHeader: return u'<img src="%s" height="30"/>' % self.imageHeader.get('url') else: return u'' image_tag.short_description = 'Image' image_tag.allow_tags = True def user_voted(self): content_type = ContentType.objects.get_for_model(self.__class__) try: voted = Vote.objects.get(object_id=self.id, content_type=content_type, user=User.objects.get(id=self.user_id), vote=1) return True except Exception, e: return False
class Post(TimeStampedModel): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(_('Title'), max_length=200) slug = models.SlugField(_('Slug'), max_length=200, unique=True) description = MartorField(_('Description')) tags = models.ManyToManyField('Tag') keywords = models.CharField(_('Keywords'), null=True, blank=True, max_length=200, help_text=_('Keywords sparate by comma.')) meta_description = models.TextField(_('Meta Description'), null=True, blank=True) is_featured = models.BooleanField(_('Is Featured?'), default=False) publish = models.BooleanField(_('Publish'), default=True) rating = RatingField(can_change_vote=True) objects = PostQuerySet.as_manager() def __str__(self): return self.title # @models.permalink def get_absolute_url(self): return reverse('posts_detail', kwargs={'slug': self.slug}) def get_visitors(self): return Visitor.objects.filter(post=self) @property def total_visitors(self): return self.get_visitors().count() def get_favorites(self): return Favorite.objects.filter(post=self) @property def total_favorites(self): return self.get_favorites().count() def save(self, *args, **kwargs): """ generate an unique slug """ if self.slug: # edit if slugify(self.title) != self.slug: self.slug = generate_unique_slug(Post, self.title) else: # create self.slug = generate_unique_slug(Post, self.title) super(Post, self).save(*args, **kwargs) def delete(self, *args, **kwargs): """ run delete action for instanced objects """ Visitor.objects.filter(post=self).delete() Favorite.objects.filter(post=self).delete() Vote.objects.filter(content_type__model='post', object_id=self.id).delete() super(Post, self).delete(*args, **kwargs) class Meta: verbose_name = _('Detail Post') verbose_name_plural = _('Posts') ordering = ['-created']