def ready(self): from django_comments.moderation import moderator from zinnia.signals import connect_entry_signals from zinnia.signals import connect_discussion_signals from zinnia.moderator import EntryCommentModerator entry_klass = self.get_model('Entry') # Register the comment moderator on Entry moderator.register(entry_klass, EntryCommentModerator) # Connect the signals connect_entry_signals() connect_discussion_signals()
def ready(self): from django_comments.moderation import moderator from zinnia.signals import connect_entry_signals from zinnia.signals import connect_discussion_signals from zinnia.moderator import EntryCommentModerator entry_klass = self.get_model('Entry') # Register the comment moderator on Entry moderator.register(entry_klass, EntryCommentModerator) # Connect the signals connect_entry_signals() connect_discussion_signals()
def moderate_model(ParentModel, publication_date_field=None, enable_comments_field=None): """ Register a parent model (e.g. ``Blog`` or ``Article``) that should receive comment moderation. :param ParentModel: The parent model, e.g. a ``Blog`` or ``Article`` model. :param publication_date_field: The field name of a :class:`~django.db.models.DateTimeField` in the parent model which stores the publication date. :type publication_date_field: str :param enable_comments_field: The field name of a :class:`~django.db.models.BooleanField` in the parent model which stores the whether comments are enabled. :type enable_comments_field: str """ attrs = { "auto_close_field": publication_date_field, "auto_moderate_field": publication_date_field, "enable_field": enable_comments_field, } ModerationClass = type(ParentModel.__name__ + "Moderator", (FluentCommentsModerator,), attrs) moderator.register(ParentModel, ModerationClass)
def moderate_model(ParentModel, publication_date_field=None, enable_comments_field=None): """ Register a parent model (e.g. ``Blog`` or ``Article``) that should receive comment moderation. :param ParentModel: The parent model, e.g. a ``Blog`` or ``Article`` model. :param publication_date_field: The field name of a :class:`~django.db.models.DateTimeField` in the parent model which stores the publication date. :type publication_date_field: str :param enable_comments_field: The field name of a :class:`~django.db.models.BooleanField` in the parent model which stores the whether comments are enabled. :type enable_comments_field: str """ attrs = { 'auto_close_field': publication_date_field, 'auto_moderate_field': publication_date_field, 'enable_field': enable_comments_field, } ModerationClass = type(ParentModel.__name__ + 'Moderator', (FluentCommentsModerator,), attrs) moderator.register(ParentModel, ModerationClass)
def test_comment_count_denormalization(self): class AllIsSpamModerator(EntryCommentModerator): spam_checker_backends = [ 'zinnia.spam_checker.backends.all_is_spam' ] class NoMailNoSpamModerator(EntryCommentModerator): def email(self, *ka, **kw): pass def moderate(self, *ka, **kw): return False datas = { 'name': 'Jim Bob', 'email': '*****@*****.**', 'url': '', 'comment': 'This is my comment' } f = CommentForm(self.entry) datas.update(f.initial) url = reverse('comments-post-comment') moderator_stack.unregister(Entry) moderator_stack.register(Entry, AllIsSpamModerator) self.assertEqual(self.entry.comment_count, 0) connect_discussion_signals() self.client.post(url, datas) entry_reloaded = Entry.objects.get(pk=self.entry.pk) self.assertEqual(entry_reloaded.comment_count, 0) moderator_stack.unregister(Entry) moderator_stack.register(Entry, NoMailNoSpamModerator) datas['comment'] = 'This a published comment' self.client.post(url, datas) disconnect_discussion_signals() entry_reloaded = Entry.objects.get(pk=self.entry.pk) self.assertEqual(entry_reloaded.comment_count, 1)
def test_comment_count_denormalization(self): class AllIsSpamModerator(EntryCommentModerator): spam_checker_backends = [ 'zinnia.spam_checker.backends.all_is_spam'] class NoMailNoSpamModerator(EntryCommentModerator): def email(self, *ka, **kw): pass def moderate(self, *ka, **kw): return False datas = {'name': 'Jim Bob', 'email': '*****@*****.**', 'url': '', 'comment': 'This is my comment'} f = CommentForm(self.entry) datas.update(f.initial) url = reverse('comments-post-comment') moderator_stack.unregister(Entry) moderator_stack.register(Entry, AllIsSpamModerator) self.assertEqual(self.entry.comment_count, 0) connect_discussion_signals() self.client.post(url, datas) entry_reloaded = Entry.objects.get(pk=self.entry.pk) self.assertEqual(entry_reloaded.comment_count, 0) moderator_stack.unregister(Entry) moderator_stack.register(Entry, NoMailNoSpamModerator) datas['comment'] = 'This a published comment' self.client.post(url, datas) disconnect_discussion_signals() entry_reloaded = Entry.objects.get(pk=self.entry.pk) self.assertEqual(entry_reloaded.comment_count, 1)
def test_integrity_error_on_duplicate_spam_comments(self): class AllIsSpamModerator(EntryCommentModerator): spam_checker_backends = [ 'zinnia.spam_checker.backends.all_is_spam'] moderator_stack.unregister(Entry) moderator_stack.register(Entry, AllIsSpamModerator) datas = {'name': 'Jim Bob', 'email': '*****@*****.**', 'url': '', 'comment': 'This is my comment'} f = CommentForm(self.entry) datas.update(f.initial) url = reverse('comments-post-comment') self.assertEqual(self.entry.comment_count, 0) connect_discussion_signals() self.client.post(url, datas) self.client.post(url, datas) disconnect_discussion_signals() self.assertEqual(comments.get_model().objects.count(), 1) entry_reloaded = Entry.objects.get(pk=self.entry.pk) self.assertEqual(entry_reloaded.comment_count, 0)
from django.contrib.auth.models import User from django.db import models from django_comments.moderation import CommentModerator, moderator from taggit.managers import TaggableManager from django.core.urlresolvers import reverse class Blog(models.Model): title = models.CharField(max_length=100, unique_for_date="posted", verbose_name="Загаловак") description = models.TextField(verbose_name="Скарочаны змест") content = models.TextField(verbose_name="Змест") posted = models.DateTimeField(auto_now_add=True, db_index=True, verbose_name="Апублікавана") is_commentable = models.BooleanField(default=True, verbose_name="Дазвол каментавання") tags = TaggableManager(blank=True, verbose_name="Тэгі") user = models.ForeignKey(User, editable=False) def get_absolute_url(self): return reverse("blog_detail", kwargs={"pk": self.pk}) class Meta: ordering = ["-posted"] verbose_name = "артыкул блогу" verbose_name_plural = "артыкулы блогу" class BlogModerator(CommentModerator): email_notification = True enable_field = "is_commentable" moderator.register(Blog, BlogModerator)
from comments_moderation.models import EmailFilter from django.contrib import admin from django_comments.moderation import CommentModerator, moderator from webmap.models import Poi class PoiModerator(CommentModerator): def moderate(self, comment, content_object, request): if EmailFilter.objects.filter(email=comment.user_email, active=True).count() > 0: return True email_filter = EmailFilter(email=comment.user_email, active=False) email_filter.save() return False class BlacklistAdmin(admin.ModelAdmin): list_display = ('email', 'active') admin.site.register(EmailFilter, BlacklistAdmin) moderator.register(Poi, PoiModerator)
from django_comments.moderation import CommentModerator, moderator from clickclick.models import Photo, PhotoSet class PhotoModerator(CommentModerator): email_notification = False def allow(self, comment, content_object, request): "Returns True if both the super method is true and comments are enabled on the photoset." return (super(PhotoModerator, self).allow(comment, content_object, request) and content_object.photoset.comments_enabled != PhotoSet.COMMENTS_OFF) def moderate(self, comment, content_object, request): "Returns True if either the super method is True or comments on the photoset are moderated." return (super(PhotoModerator, self).moderate(comment, content_object, request) or content_object.photoset.comments_enabled == PhotoSet.COMMENTS_MODERATED) moderator.register(Photo, PhotoModerator)
'month': self.month, 'day': self.day, 'slug': self.slug, }) def make_references(self): """ Sets all the Encyclopedia Topics the text of this letter (and footnotes) refers to. Saves them to the database. """ self.topics.clear() # Get a list of all the Topic IDs mentioned in text and footnotes: ids = re.findall(r'pepysdiary.com\/encyclopedia\/(\d+)\/', '%s %s' % ( self.text, self.footnotes)) # Make sure list of Topic IDs is unique: # From http://stackoverflow.com/a/480227/250962 seen = set() seen_add = seen.add unique_ids = [id for id in ids if id not in seen and not seen_add(id)] for id in unique_ids: topic = Topic.objects.get(pk=id) topic.letter_references.add(self) class LetterModerator(CommentModerator): email_notification = False enable_field = 'allow_comments' moderator.register(Letter, LetterModerator)
class Quote(models.Model): """每日一句""" date = models.DateField() quote = models.CharField(max_length=200, verbose_name='名言') translation = models.CharField(max_length=200, verbose_name='翻译') source = models.CharField(max_length=200, verbose_name='出处') class Meta: db_table = 'df_quote' verbose_name = '每日一句' verbose_name_plural = verbose_name def __str__(self): return self.quote # 控制评论行为 from django_comments.moderation import CommentModerator, moderator class ArticleModerator(CommentModerator): email_notification = True auto_close_field = 'create_time' # Close the comments after 365 days. close_after = 365 enable_field = 'enable_comments' moderator.register(Article, ArticleModerator)
year_refs = [ref.year, []] month_refs[1].append(ref) prev_year = ref.year prev_yearmonth = ref.year + ref.month_b if len(year_refs) > 0: year_refs[1].append(month_refs) refs.append(year_refs) return refs class TopicModerator(CommentModerator): email_notification = False enable_field = 'allow_comments' moderator.register(Topic, TopicModerator) def topic_categories_changed(sender, **kwargs): """ When we add or remove categories on this topic, we need to re-set those categories' topic counts. """ if kwargs['reverse'] == False: # We're changing the categories on a topic. if kwargs['action'] == 'pre_clear': # Before we do anything, # store the PKs of the current categories on this topic. kwargs['instance']._original_categories_pks = [ c.pk for c in kwargs['instance'].categories.all() ]
verbose_name = _('Event') verbose_name_plural = _('Events') def __str__(self): return self.title def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.title) now = timezone.now() if self.status == self.STATUS_PUBLIC: self.pub_date = now super(Event, self).save(*args, **kwargs) @models.permalink def get_absolute_url(self): return ('event_detail', (), {'slug': self.slug}) class EventModerator(CommentModerator): email_notification = True enable_field = 'enable_comments' # auto_close_field = 'publish' # close_after = 7 moderator.register(Event, EventModerator)
tags = TaggableManager(through=TaggedPost, blank=True) objects = models.Manager() published = PublicPostManager() class Meta: ordering = ('-pub_date', ) verbose_name = _('post') verbose_name_plural = _('posts') app_label = 'logos' def __unicode__(self): return self.title def get_absolute_url(self): return reverse('logos_post_detail', kwargs={ 'year': self.pub_date.year, 'month': self.pub_date.strftime('%b').lower(), 'day': self.pub_date.day, 'slug': self.slug, }) class PostModerator(CommentModerator): enable_field = 'allow_comments' email_notification = True moderator.register(Post, PostModerator)
def setUp(self): super(BogofilterTests, self).setUp() self.article = Article.objects.get(pk=1) # register our moderator if Article not in moderator._registry: moderator.register(Article, BogofilterCommentModerator) # training spam self.c1 = BogofilterComment.objects.create( content_type = CT(Article), object_pk = "1", site = Site.objects.get_current(), comment = "Tirage du tarot de marseille gratuit en ligne horoscope homme balance 2011", user_name = "voyance gratuite", user_email = "*****@*****.**", user_url = "http://www.alainfauquet.fr/", ip_address = "85.254.74.3", ) self.c1.mark_spam() self.c2 = BogofilterComment.objects.create( content_type = CT(Article), object_pk = "1", site = Site.objects.get_current(), comment = "Tirage du tarot de marseille gratuit en ligne horoscope homme balance 2011", user_name = "voyance gratuite en ligne", user_email = "*****@*****.**", user_url = "http://www.annonces-flash.com/", ip_address = "85.254.75.75", ) self.c2.mark_spam() self.c3 = BogofilterComment.objects.create( content_type = CT(Article), object_pk = "1", site = Site.objects.get_current(), comment = "Voyance sante gratuite tirag tarot gratuit", user_name = "voyance gratuite", user_email = "*****@*****.**", user_url = "http://www.annonces-flash.com/", ip_address = "85.254.81.91", ) self.c3.mark_spam() self.c4 = BogofilterComment.objects.create( content_type = CT(Article), object_pk = "1", site = Site.objects.get_current(), comment = "Voyance pendule gratuite horoscope christine haas 2011", user_name = "voyance", user_email = "*****@*****.**", user_url = "http://www.alainfauquet.fr/", ip_address = "85.254.81.202", ) self.c4.mark_spam() # training ham self.c7 = BogofilterComment.objects.create( content_type = CT(Article), object_pk = "1", site = Site.objects.get_current(), comment = "Great post. Saved me a ton of time. Thanks.", user_name = "Reg Doe", user_email = "*****@*****.**", user_url = "http://www.regdoe.ca/", ip_address = "95.47.208.0", ) self.c7.mark_ham() self.c8 = BogofilterComment.objects.create( content_type = CT(Article), object_pk = "1", site = Site.objects.get_current(), comment = "This is just awesome! Thanks for the defs.", user_name = "Shivi", user_email = "*****@*****.**", user_url = "", ip_address = "121.160.222.97", ) self.c8.mark_ham() self.c9 = BogofilterComment.objects.create( content_type = CT(Article), object_pk = "1", site = Site.objects.get_current(), comment = "Worked for me thanks", user_name = "raga", user_email = "*****@*****.**", user_url = "", ip_address = "140.240.54.144", ) self.c9.mark_ham() self.c10 = BogofilterComment.objects.create( content_type = CT(Article), object_pk = "1", site = Site.objects.get_current(), comment = "Nice post. Very concise and useful. I like your approach of attaching custom attributes to the QPushButton. I tend to do this sort of thing using lambda. I'm not sure if one way is better than the other, just an observation: button.clicked.connect(lambda: self.listen(name, url)) http://codrspace.com/durden/using-lambda-with-pyqt-signals/ I've also seen people solve this problem with functools.partial: http://eli.thegreenplace.net/2011/04/25/passing-extra-arguments-to-pyqt-slot/", user_name = "Luki Lii", user_email = "*****@*****.**", user_url = "http://lukilii.me/", ip_address = "137.31.79.10", ) self.c10.mark_ham() self.c11 = BogofilterComment.objects.create( content_type = CT(Article), object_pk = "1", site = Site.objects.get_current(), comment = "Yes, using the lambda is a valid alternative but self.sender() no longer works inside self.listen() - or inside the lambda for that matter.", user_name = "Stefan Talpalaru", user_email = "*****@*****.**", user_url = "", ip_address = "78.23.54.6", ) self.c11.mark_ham() self.c12 = BogofilterComment.objects.create( content_type = CT(Article), object_pk = "1", site = Site.objects.get_current(), comment = "Neat article. For future reference: http://blog.scoopz.com/2011/05/05/listen-to-any-bbc-radio-live-stream-using-vlc-including-radio-1-and-1xtra/", user_name = "carlisle", user_email = "*****@*****.**", user_url = "", ip_address = "177.208.61.148", ) self.c12.mark_ham() self.c13 = BogofilterComment.objects.create( content_type = CT(Article), object_pk = "1", site = Site.objects.get_current(), comment = "Thank you!", user_name = "Gordon", user_email = "*****@*****.**", user_url = "http://cafeofbrokenarms.com/", ip_address = "130.106.173.235", ) self.c13.mark_ham() self.c14 = BogofilterComment.objects.create( content_type = CT(Article), object_pk = "1", site = Site.objects.get_current(), comment = "Thank you for this great bit of code. It has worked for the two websites I have used this in. Your article is very informative and written with a very fun tone. Thanks!", user_name = "Rachel", user_email = "*****@*****.**", user_url = "", ip_address = "172.13.9.220", ) self.c14.mark_ham() # test spam self.client.post("/post/", self.CommentFormData({ "comment" : "Horoscope yahoo du jour l ascendant astrologique", "name" : "voyance", "email" : "*****@*****.**", "url" : "http://www.annonces-flash.com/", }), REMOTE_ADDR="85.254.82.164") self.c5 = BogofilterComment.objects.order_by('-submit_date')[0] self.client.post("/post/", self.CommentFormData({ "comment" : "Accouchement lune calcul horoscope femme scorpion", "name" : "voyance gratuite en ligne", "email" : "*****@*****.**", "url" : "http://www.annonces-flash.com/", }), REMOTE_ADDR="85.254.153.161") self.c6 = BogofilterComment.objects.order_by('-submit_date')[0] # test ham self.client.post("/post/", self.CommentFormData({ "comment" : "Hi, thanks for the blog. Can this project still work with facebook oauth 2.0 and kay framework 3? because I see the project is pretty old (3years). I try to use Kay ext for facebook/twitter but it does not work. Therefore, I hope your project can help me.", "name" : "Nam", "email" : "*****@*****.**", "url" : "", }), REMOTE_ADDR="48.131.92.5") self.c28 = BogofilterComment.objects.order_by('-submit_date')[0] self.client.post("/post/", self.CommentFormData({ "comment" : "This post was very useful. Having my logs in UTC will be excellent.", "name" : "Tim Wilder", "email" : "*****@*****.**", "url" : "", }), REMOTE_ADDR="207.145.42.4") self.c29 = BogofilterComment.objects.order_by('-submit_date')[0] self.client.post("/post/", self.CommentFormData({ "comment" : "One other thing: since the lambda's body is not evalued until the signal is triggered, a naive implementation would make all the buttons play the last radio station (because 'name' and 'url' point to it at the end of the loop). The only way it works is something like this: button.clicked.connect(lambda _button=button, _name=name, _url=url: self.listen(_button, _name, _url)) Yes, it's ugly...", "name" : "Stefan Talpalaru", "email" : "*****@*****.**", "url" : "http://stefantalpalaru.wordpress.com", }), REMOTE_ADDR="86.8.17.57") self.c30 = BogofilterComment.objects.order_by('-submit_date')[0]
def __str__(self): return str(self.rating) def display(self): return self.flag # Автомодератор для комментариев class ProductModerator(CommentModerator): email_notification = False enable_field = 'enable_comments' auto_moderate_field = 'created' moderate_after = 0 moderator.register(Product, ProductModerator) def sender_mail(theme, text): send_mail(theme, text, settings.SERVER_EMAIL, [settings.STUFF_EMAIL], fail_silently=False) # Отправка письма по событию post_save() def notify_of_comment(sender, instance, **kwargs): theme = 'Оставлен новый комментарий о товаре' link = 'localhost:8000' + instance.get_content_object_url() text = 'от: %s. \nОтзыв: %s. \nссылка на товар: %s \nНапоминание: необходимо разрешить показывать' \ ' этот отзыв на сайте или удалить...' % (instance.user_name.title(), instance.comment.capitalize(), link)
return "%s bookmarked by %s" % (self.snippet, self.user) def save(self, *args, **kwargs): super(Bookmark, self).save(*args, **kwargs) self.snippet.update_bookmark_count() def delete(self, *args, **kwargs): super(Bookmark, self).delete(*args, **kwargs) self.snippet.update_bookmark_count() class SnippetModerator(SpamFighterModerator): # Regular options by Django's contributed CommentModerator email_notification = True # Spam fighter options: # Check with Akismet for spam akismet_check = True # If Akismet marks this message as spam, delete it instantly (False) or # add it the comment the moderation queue (True). Default is True. akismet_check_moderate = True # Do a keyword check keyword_check = True # If a keyword is found, delete it instantly (False) or add the comment to # the moderation queue (True). Default is False. keyword_check_moderate = True moderator.register(Snippet, SnippetModerator) start_listening()
from comments_moderation.models import EmailFilter from django.contrib import admin from django_comments.moderation import CommentModerator, moderator from webmap.models import Poi class PoiModerator(CommentModerator): def moderate(self, comment, content_object, request): if EmailFilter.objects.filter(email=comment.user_email, active=True).count() > 0: return True email_filter = EmailFilter(email=comment.user_email, active=False) email_filter.save() return False class BlacklistAdmin(admin.ModelAdmin): list_display = ('email', 'active') admin.site.register(EmailFilter, BlacklistAdmin) moderator.register(Poi, PoiModerator)
def content_tiny_url(content): regex_url = r"http:\/\/([\w.]+\/?)\S*" for match in re.finditer(regex_url, content): url = match.group(0) content = content.replace(url, tiny_url(url)) return content def config_name(sender, instance, created, **kwargs): if created: temp = Configuration.objects.all() if temp.count() > 2: raise Exception( "There can only be one configuration entry, \ thus only one theme. Sorry!" ) class PostModerator(CommentModerator): email_notification = True enable_field = "enable_comments" moderator.register(Story, PostModerator) moderator.register(Article, PostModerator) moderator.register(Gallery, PostModerator) post_save.connect(config_name, sender=Configuration)
self.slug = slugify(self.title + "_" + self.keywords) super(BlogPost, self).save(*args, **kwargs) def get_absolute_url(self): return '/' + self.category.slug + '/' + self.slug # def get_absolute_url(self): # return reverse('blog', args=[category.slug+"/"+self.slug]) class BlogPostModerator(CommentModerator): email_notification = True enable_field = 'enable_comments' moderator.register(BlogPost, BlogPostModerator) class BlogCategory(models.Model): title = models.CharField(max_length=100, db_index=True) slug = models.SlugField(max_length=100, db_index=True) def __str__(self): return f'{self.title}' class Manufacturer(models.Model): name = models.CharField(max_length=100) website = models.CharField(max_length=100, null=True, blank=True) updated = models.DateField(null=True, blank=True) visible = models.BooleanField(default=False, null=True, blank=True)
class Blog(models.Model): title = models.CharField(maxlength=250) body = models.TextField() pub_date = models.DateField() enable_comments = models.BooleanField() # Здесь мы создаем модель Blog, в которую будут записываться статьи блага. В поле # pub_date будет храниться дата публикации статьи - мы указали, что значение в это # поле станет заноситься автоматически при создании новой записи. А в поле # еnаble_comments будет храниться признак того, разрешены ли для статьи # комментарии, значение по умолчанию этого поля - тrue. from django_comments.moderation import CommentModerator, moderator class BlogModerator(CommentModerator): email_notification = True enable_field = 'enable_comments' auto_moderate_field = 'pub_date' moderate_after = 30 # А здесь создаем автомодератор для модели Blog. Активизируем автоматическую # рассылку уведомлений о вновь добавленных комментариях, задаем возможность # запрета комментирования и указываем, что все комментарии, добавленные спустя # 30 дней после создания статьи, должны изначально делаться скрытыми. # После объявления класса автомодератора его следует привязать к модели. Для это # го мы вызовем не возвращающий результата метод register класса moderator, объ # явленного в том же модуле django_comments.moderation. Первым парамет # ром этому методу передадим класс модели, а вторым - класс автомодератора, # который к ней привязывается: moderator.register(Blog, BlogModerator)
ordering = ['-date_published', ] def __unicode__(self): return u'%s' % (self.title) def save(self, *args, **kwargs): self.intro_html = markdown(self.intro) self.text_html = markdown(self.text) if self.date_published is None and \ self.status == self.STATUS_PUBLISHED: # If we're published, and the date_published hasn't been set, # then set it. self.date_published = timezone.now() super(Post, self).save(*args, **kwargs) def get_absolute_url(self): return reverse('post_detail', kwargs={ 'year': self.date_published.strftime('%Y'), 'month': self.date_published.strftime('%m'), 'day': self.date_published.strftime('%d'), 'pk': self.pk, }) class PostModerator(CommentModerator): email_notification = False enable_field = 'allow_comments' moderator.register(Post, PostModerator)
subject = "[%s] Forum posting" % project.short_name # thread url: http://localhost:8000/projects/TestProject/thread/2/ url = reverse('thread_detail', kwargs={ 'project_short_name':project.short_name.lower(), 'thread_id':thread.id }) url = request.build_absolute_uri(url) # specific comment url: http://localhost:8000/projects/TestProject/thread/2/?c=17 # a) send plain text email #message = "User: %s\n Thread: %s\n Comment: %s\n" % (user, url, comment.comment) # b) send html formatted email # parse comment content to build images full URLs message = comment.comment # src="/site_media/projects/testproject/Unknown.jpeg" groups = list( re.finditer('src=\"[^\"]+\"', message) ) paths = [] # list of (relpath, abspath) to replace after the full message is parsed for group in groups: relpath = message[group.start()+5:group.end()-1] abspath = request.build_absolute_uri(relpath) paths.append( (relpath, abspath) ) # replace all for path in paths: message = message.replace(path[0], path[1]) message = "User: %s<br/>Forum Thread: %s<p/>New Comment: %s" % (user, url, message) # send email for admin in project.getAdminGroup().user_set.all(): notify(admin, subject, message, mime_type='html') moderator.register(ForumThread, ForumModerator)
def __unicode__(self): if self.first_name != "": return "%s %s" % (self.first_name, self.last_name) return self.username class FileUpload(models.Model): f = models.FileField(upload_to="files/%Y-%m-%d/") class ProjectModerator(CommentModerator): moderate_after = -1 moderator.register(Project, ProjectModerator) class Address(models.Model): school = models.CharField(max_length=255) town = models.CharField(max_length=255) state = models.CharField(max_length=255, verbose_name="State or Province") country = models.CharField(max_length=255) phone = models.CharField(max_length=255) teacher = models.OneToOneField(settings.AUTH_USER_MODEL, primary_key=True) class Meta: verbose_name_plural = "Addresses" class ApplicationTheme(models.Model):
class Meta: ordering = ['-date_published', ] def __unicode__(self): return u'%s' % (self.title) def save(self, *args, **kwargs): self.intro_html = markdown(self.intro) self.text_html = markdown(self.text) if self.date_published is None and self.status == self.STATUS_PUBLISHED: # If we're published, and the date_published hasn't been set, # then set it. self.date_published = timezone.now() super(Article, self).save(*args, **kwargs) def get_absolute_url(self): return reverse('article_detail', kwargs={ 'year': self.date_published.strftime('%Y'), 'month': self.date_published.strftime('%m'), 'day': self.date_published.strftime('%d'), 'slug': self.slug, }) class ArticleModerator(CommentModerator): email_notification = False enable_field = 'allow_comments' moderator.register(Article, ArticleModerator)
"""Models for Zinnia""" from django_comments.moderation import moderator from zinnia.models.entry import Entry from zinnia.models.author import Author from zinnia.models.category import Category from zinnia.signals import connect_entry_signals from zinnia.signals import connect_discussion_signals from zinnia.moderator import EntryCommentModerator # Here we import the Zinnia's Model classes # to register the Models at the loading, not # when the Zinnia's URLs are parsed. Issue #161. __all__ = [Entry.__name__, Author.__name__, Category.__name__] # Register the comment moderator on Entry if Entry not in moderator._registry: moderator.register(Entry, EntryCommentModerator) # Connect the signals connect_entry_signals() connect_discussion_signals()
def testRegisterExistingModel(self): moderator.register(Entry, EntryModerator1) self.assertRaises(AlreadyModerated, moderator.register, Entry, EntryModerator1)
def register(model): moderator.register(model, FilteredCommentsModerator)
def testEmailNotification(self): with override_settings(MANAGERS=("*****@*****.**",)): moderator.register(Entry, EntryModerator1) self.createSomeComments() self.assertEqual(len(mail.outbox), 2)
name = models.CharField(max_length=50) slug = models.SlugField(unique=True, help_text="Suggested value automatically generated from title. Must be unique.") day_of_week = models.IntegerField(choices=DAY_OF_WEEK, default=0) run_time = models.CharField(max_length=25, help_text="Time of run (ex. 6:30 PM)") location = models.ForeignKey('locations.Location', blank=True, null=True) details = models.TextField() contact = models.ForeignKey('members.Member') active = models.BooleanField(default=True) objects = RunManager() class Meta: ordering = ['day_of_week'] verbose_name = _('Run') verbose_name_plural = _('Runs') def __str__(self): return '{0}: {1}'.format(self.get_day_of_week_display(), self.name) @models.permalink def get_absolute_url(self): return ('run_detail', (), {'slug': self.slug}) class RunModerator(CommentModerator): email_notification = True enable_field = 'enable_comments' moderator.register(Run, RunModerator)
def testCommentsEnabled(self): moderator.register(Entry, EntryModerator2) self.createSomeComments() self.assertEqual(Comment.objects.all().count(), 1)
# From http://stackoverflow.com/a/480227/250962 seen = set() seen_add = seen.add unique_ids = [id for id in ids if id not in seen and not seen_add(id)] for id in unique_ids: topic = Topic.objects.get(pk=id) topic.letter_references.add(self) @property def short_date(self): """ Shorter than self.display_date, like '27 April 1665'. """ return '%s %s %s' % (self.day_e, self.month_b, self.year) @property def full_title(self): """ Uniquish title including correspondents and date, like '27 April 1665, Samuel Pepys to John Evelyn'. """ return '%s, %s' % (self.short_date, self.title) class LetterModerator(CommentModerator): email_notification = False enable_field = 'allow_comments' moderator.register(Letter, LetterModerator)
def testAutoCloseField(self): moderator.register(Entry, EntryModerator3) self.createSomeComments() self.assertEqual(Comment.objects.all().count(), 0)
def register(model): """Just a wrapper around django_comments.moderation.register. It's only argument is the model for comment moderation.""" moderator.register(model, CookieModerator)
def testAutoModerateFieldImmediate(self): moderator.register(Entry, EntryModerator5) c1, c2 = self.createSomeComments() self.assertEqual(c2.is_public, False)
refs.append(year_refs) year_refs = [ref.year, []] month_refs[1].append(ref) prev_year = ref.year prev_yearmonth = ref.year + ref.month_b if len(year_refs) > 0: year_refs[1].append(month_refs) refs.append(year_refs) return refs class TopicModerator(CommentModerator): email_notification = False enable_field = 'allow_comments' moderator.register(Topic, TopicModerator) def topic_categories_changed(sender, **kwargs): """ When we add or remove categories on this topic, we need to re-set those categories' topic counts. """ if kwargs['reverse'] == False: # We're changing the categories on a topic. if kwargs['action'] == 'pre_clear': # Before we do anything, # store the PKs of the current categories on this topic. kwargs['instance']._original_categories_pks = [ c.pk for c in kwargs['instance'].categories.all()]
class Meta: get_latest_by = 'created_at' verbose_name_plural = ('Entries') def __unicode__(self): return self.title def save(self, *args, **kwargs): self.slug = self.slugify_title() if self.is_micro: # forcing no excerpt for micro entries self.excerpt = self.excerpt_html = "" else: self.excerpt_html = markdown(self.excerpt) self.content_html = markdown(self.content) super(Entry, self).save(*args, **kwargs) @models.permalink def get_absolute_url(self): return ( 'blog.views.entry_detail', (), {'entry_id': self.id, 'slug': self.slug}, ) class EntryModerator(CommentModerator): enable_field = 'enable_comments' moderator.register(Entry, EntryModerator)
#Тип объекта item_type = models.CharField(db_index=True, max_length=2, verbose_name='Тип', choices=ITEM_TYPES, default=TOP) def __str__(self): return self.name def is_leaf(self): return self.item_type == self.LEAF def get_children(self): if self.is_leaf(): return None else: children = Item.objects.filter(parent = self) return children @staticmethod def get_tops(): tops = Item.objects.filter(item_type = Item.TOP) return tops def get_url(self): return reverse('item', kwargs={'pk': self.pk}) #from django.contrib.comments.moderation import CommentModerator, moderator from django_comments.moderation import CommentModerator, moderator class ItemModerator(CommentModerator): email_notification = True moderator.register(Item, ItemModerator)
def testRegisterExistingModel(self): moderator.register(Entry, EntryModerator1) self.assertRaises(AlreadyModerated, moderator.register, Entry, EntryModerator1)
from django_comments.moderation import CommentModerator, moderator from clickclick.models import Photo, PhotoSet class PhotoModerator(CommentModerator): email_notification = False def allow(self, comment, content_object, request): "Returns True if both the super method is true and comments are enabled on the photoset." return ( super(PhotoModerator, self).allow(comment, content_object, request) and content_object.photoset.comments_enabled != PhotoSet.COMMENTS_OFF) def moderate(self, comment, content_object, request): "Returns True if either the super method is True or comments on the photoset are moderated." return (super(PhotoModerator, self).moderate(comment, content_object, request) or content_object.photoset.comments_enabled == PhotoSet.COMMENTS_MODERATED) moderator.register(Photo, PhotoModerator)
def testCommentsEnabled(self): moderator.register(Entry, EntryModerator2) self.createSomeComments() self.assertEqual(Comment.objects.all().count(), 1)
if image._size > int(settings.MAX_UPLOAD_SIZE): raise forms.ValidationError( _(u'Please keep filesize under %s. Current filesize %s' ) % (filesizeformat(settings.MAX_UPLOAD_SIZE), filesizeformat(content._size))) else: raise forms.ValidationError(_(u'File type is not supported')) return image def __str__(self): return self.colleges class Cluster(models.Model): name = models.CharField(max_length=100) users = models.ManyToManyField(User, related_name='colleges') def get_members(self): return "\n".join([u.username for u in self.users.all()]) class ReviewModerator(CommentModerator): email_notification = True auto_close_field = 'posted_date' # Close the comments after 7 days. close_after = 7 moderator.register(Review, ReviewModerator) # Create your models here.
def testAutoModerateFieldImmediate(self): moderator.register(Entry, EntryModerator5) c1, c2 = self.createSomeComments() self.assertEqual(c2.is_public, False)
def get_race_reports(self): return self.report_set.all() @cached_property def is_finished(self): return not self.result_set.count() == 0 class RaceModerator(CommentModerator): email_notification = True enable_field = 'enable_comments' auto_close_field = 'start_datetime' close_after = 30 moderator.register(Race, RaceModerator) @python_2_unicode_compatible class Registration(models.Model): """Registration model.""" race = models.ForeignKey('races.Race') description = models.CharField(max_length=100, blank=True, null=True) reg_date = models.DateField('Registration Date') end_date = models.DateField('End Date', blank=True, null=True) reg_cost = models.IntegerField('Registration Cost') class Meta: verbose_name = _('Registration Dates') verbose_name_plural = _('Registration Dates')
class Meta: verbose_name = "тавар" verbose_name_plural = "тавары" class GoodImage(models.Model): good = models.ForeignKey(Good) image = models.ImageField(upload_to="goods/detail", verbose_name="Дадатковая выява") def save(self, *args, **kwargs): try: this_record = GoodImage.objects.get(pk=self.pk) if this_record.image != self.image: this_record.image.delete(save=False) except: pass super(GoodImage, self).save(*args, **kwargs) def delete(self, *args, **kwargs): self.image.delete(save=False) super(GoodImage, self).delete(*args, **kwargs) class Meta: verbose_name = "выява да тавару" verbose_name_plural = "выявы да тавару" class GoodModerator(CommentModerator): email_notification = True moderator.register(Good, GoodModerator)
def testEmailNotification(self): with override_settings(MANAGERS=("*****@*****.**", )): moderator.register(Entry, EntryModerator1) self.createSomeComments() self.assertEqual(len(mail.outbox), 2)
class BookModerator(CommentModerator): email_notification = True enable_field = 'enable_comments' moderator.register(Book, CommentModerator)
def testAutoCloseField(self): moderator.register(Entry, EntryModerator3) self.createSomeComments() self.assertEqual(Comment.objects.all().count(), 0)
def register(model): """Just a wrapper around django_comments.moderation.register. It's only argument is the model for comment moderation.""" moderator.register(model, CookieModerator)
return "{}".format(self.username) class FileUpload(models.Model): """All files uploaded by users for projects, principally screenshots, project data.""" file_path = models.FileField(upload_to='files/%Y-%m-%d/') class ProjectModerator(CommentModerator): """Should be replaced by msg being created by ryaholm.""" moderate_after = -1 moderator.register(Project, ProjectModerator) class Address(models.Model): """Information about where a student goes to school.""" school = models.CharField(max_length=255) town = models.CharField(max_length=255) state = models.CharField(max_length=255, verbose_name='State or Province') country = models.CharField(max_length=255) phone = models.CharField(max_length=255) teacher = models.OneToOneField(settings.AUTH_USER_MODEL, primary_key=True, on_delete=models.CASCADE) class Meta: verbose_name_plural = "Addresses"
self.slug = slugify(self.title) now = timezone.now() if not self.pub_date and self.status == self.STATUS_PUBLIC: self.pub_date = now super(News, self).save(*args, **kwargs) @models.permalink def get_absolute_url(self): return ('news_detail', (), { 'pk': self.pk, }) def get_previous_news(self): return self.get_previous_by_publish(status__gte=self.STATUS_PUBLIC) def get_next_news(self): return self.get_next_by_publish(status__gte=self.STATUS_PUBLIC) class NewsModerator(CommentModerator): email_notification = True enable_field = 'enable_comments' auto_close_field = 'pub_date' close_after = 7 moderator.register(News, NewsModerator)
"""Models for Zinnia""" from zinnia.models.entry import Entry from zinnia.models.author import Author from zinnia.models.category import Category from zinnia.signals import connect_entry_signals from zinnia.signals import connect_discussion_signals from zinnia.moderator import EntryCommentModerator try: from django_comments.moderation import moderator except ImportError: from django.contrib.comments.moderation import moderator # Here we import the Zinnia's Model classes # to register the Models at the loading, not # when the Zinnia's URLs are parsed. Issue #161. __all__ = [Entry.__name__, Author.__name__, Category.__name__] # Register the comment moderator on Entry moderator.register(Entry, EntryCommentModerator) # Connect the signals connect_entry_signals() connect_discussion_signals()
class Type(models.Model): nom=models.CharField(max_length=200) image=models.CharField(max_length=500) def __unicode__(self): """ Cette méthode que nous définirons dans tous les modèles nous permettra de reconnaître facilement les différents objets que nous traiterons plus tard et dans l'administration """ return self.nom class ProductFilter(django_filters.FilterSet): types = django_filters.ModelMultipleChoiceFilter(queryset=Type.objects.all(), widget=forms.CheckboxSelectMultiple, conjoined=True) class Meta: model = Marque fields = ['types'] class EntryModerator(CommentModerator): auto_approve_for_superusers = False email_notification = True moderator.register(Article, EntryModerator)
class GoodImage(models.Model): good = models.ForeignKey(Good) image = models.ImageField(upload_to="goods/detail", verbose_name="Дадатковая выява") def save(self, *args, **kwargs): try: this_record = GoodImage.objects.get(pk=self.pk) if this_record.image != self.image: this_record.image.delete(save=False) except: pass super(GoodImage, self).save(*args, **kwargs) def delete(self, *args, **kwargs): self.image.delete(save=False) super(GoodImage, self).delete(*args, **kwargs) class Meta: verbose_name = "выява да тавару" verbose_name_plural = "выявы да тавару" class GoodModerator(CommentModerator): email_notification = True moderator.register(Good, GoodModerator)
return "%s bookmarked by %s" % (self.snippet, self.user) def save(self, *args, **kwargs): super(Bookmark, self).save(*args, **kwargs) self.snippet.update_bookmark_count() def delete(self, *args, **kwargs): super(Bookmark, self).delete(*args, **kwargs) self.snippet.update_bookmark_count() class SnippetModerator(SpamFighterModerator): # Regular options by Django's contributed CommentModerator email_notification = True # Spam fighter options: # Check with Akismet for spam akismet_check = True # If Akismet marks this message as spam, delete it instantly (False) or # add it the comment the moderation queue (True). Default is True. akismet_check_moderate = True # Do a keyword check keyword_check = True # If a keyword is found, delete it instantly (False) or add the comment to # the moderation queue (True). Default is False. keyword_check_moderate = True moderator.register(Snippet, SnippetModerator) start_listening()
def register(model): moderator.register(model, FilteredCommentsModerator)
from __future__ import unicode_literals from django_comments.moderation import CommentModerator, moderator from django.db import models # Create your models here. class Group(model.Models): name = models.CharField(max_length=50) description = models.CharField(max_length=100) date = models.DateTimeField(auto_now_add=True) enable_comments = models.BooleanField(default=True) def __unicode__(self): return str(self.name) class Post(model.Models): group = models.ForeignKey(Group) body = models.TextField(max_length=150) pub_date = models.DateTimeField(auto_now_add=True) def __unicode__(self): return str(self.name) class Group_Moderator(CommentModerator): enable_field = 'enable_comments' moderator.register(Group, Group_Moderator)