Login

Prevent Django newcomments spam with Akismet (reloaded)

Author:
sciyoshi
Posted:
July 17, 2009
Language:
Python
Version:
1.0
Tags:
akismet spam comments antispam newcomments
Score:
1 (after 1 ratings)

This is a rewrite of snippet #1006 to use the moderation features available in Django's comments framework. This is more customizable than the signals approach and works well if other moderation features are being used. If you want to make comments that are flagged as spam become hidden instead of deleted, change the allow() method to moderate(). See the blog post here

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
from django.contrib.comments.moderation import CommentModerator, moderator
from django.contrib.sites.models import Site
from django.conf import settings

class EntryModerator(CommentModerator):
	def check_spam(self, request, comment, key, blog_url=None, base_url=None):
		try:
			from akismet import Akismet
		except:
			return False

		if blog_url is None:
			blog_url = 'http://%s/' % Site.objects.get_current().domain

		ak = Akismet(
			key=settings.AKISMET_API_KEY,
			blog_url=blog_url
		)

		if base_url is not None:
			ak.baseurl = base_url

		if ak.verify_key():
			data = {
				'user_ip': request.META.get('REMOTE_ADDR', '127.0.0.1'),
				'user_agent': request.META.get('HTTP_USER_AGENT', ''),
				'referrer': request.META.get('HTTP_REFERER', ''),
				'comment_type': 'comment',
				'comment_author': comment.user_name.encode('utf-8'),
			}

			if ak.comment_check(comment.comment.encode('utf-8'), data=data, build_data=True):
				return True

		return False

	def allow(self, comment, content_object, request):
		allow = super(EntryModerator, self).allow(comment, content_object, request)

		# change this depending on which spam provider you want to use
		spam = self.check_spam(request, comment,
			key=settings.AKISMET_API_KEY,
		) or self.check_spam(request, comment,
			key=settings.TYPEPAD_ANTISPAM_API_KEY,
			base_url='api.antispam.typepad.com/1.1/'
		)

		return not spam and allow

moderator.register(Entry, EntryModerator)

More like this

  1. Unobtrusive comment moderation by ubernostrum 8 years ago
  2. Using Akismet/TypePad AntiSpam with Django's new comments framework by sciyoshi 6 years, 7 months ago
  3. Django Akismet by yeago 6 years, 3 months ago
  4. LinkSleeve comment moderation by zgoda 6 years, 12 months ago
  5. Akismet Webservice by sneeu 8 years ago

Comments

Please login first before commenting.