gremmie@1: """ gremmie@1: Forms for the comments application. gremmie@1: """ gremmie@1: import datetime gremmie@1: from django import forms gremmie@1: from django.conf import settings gremmie@1: from django.contrib.contenttypes.models import ContentType gremmie@1: gremmie@1: from comments.models import Comment gremmie@1: gremmie@1: COMMENT_MAX_LENGTH = getattr(settings, 'COMMENT_MAX_LENGTH', 3000) gremmie@1: gremmie@1: class CommentForm(forms.Form): gremmie@1: comment = forms.CharField(label='', gremmie@1: min_length=1, gremmie@1: max_length=COMMENT_MAX_LENGTH, gremmie@1: widget=forms.Textarea) gremmie@1: content_type = forms.CharField(widget=forms.HiddenInput) gremmie@1: object_pk = forms.CharField(widget=forms.HiddenInput) gremmie@1: gremmie@1: def __init__(self, target_object, data=None, initial=None): gremmie@1: self.target_object = target_object gremmie@1: if initial is None: gremmie@1: initial = {} gremmie@1: initial.update({ gremmie@1: 'content_type': str(self.target_object._meta), gremmie@1: 'object_pk': str(self.target_object.pk), gremmie@1: }) gremmie@1: super(CommentForm, self).__init__(data=data, initial=initial) gremmie@1: gremmie@1: def get_comment_object(self, user, ip_address): gremmie@1: """ gremmie@1: Return a new (unsaved) comment object based on the information in this gremmie@1: form. Assumes that the form is already validated and will throw a gremmie@1: ValueError if not. gremmie@1: """ gremmie@1: if not self.is_valid(): gremmie@1: raise ValueError("get_comment_object may only be called on valid forms") gremmie@1: gremmie@1: new = Comment( gremmie@1: content_type = ContentType.objects.get_for_model(self.target_object), gremmie@1: object_id = self.target_object.pk, gremmie@1: user = user, gremmie@1: comment = self.cleaned_data["comment"], gremmie@1: ip_address = ip_address, gremmie@1: is_public = True, gremmie@1: is_removed = False, gremmie@1: ) gremmie@1: gremmie@1: # Check that this comment isn't duplicate. (Sometimes people post comments gremmie@1: # twice by mistake.) If it is, fail silently by returning the old comment. gremmie@1: today = datetime.date.today() gremmie@1: possible_duplicates = Comment.objects.filter( gremmie@1: content_type = new.content_type, gremmie@1: object_id = new.object_id, gremmie@1: user = new.user, gremmie@1: creation_date__year = today.year, gremmie@1: creation_date__month = today.month, gremmie@1: creation_date__day = today.day, gremmie@1: ) gremmie@1: for old in possible_duplicates: gremmie@1: if old.comment == new.comment: gremmie@1: return old gremmie@1: gremmie@1: return new gremmie@1: gremmie@1: class Media: gremmie@1: css = { gremmie@1: 'all': ('js/markitup/skins/markitup/style.css', gremmie@1: 'js/markitup/sets/markdown/style.css') gremmie@1: } gremmie@1: js = ( gremmie@1: 'js/jquery-1.2.6.min.js', gremmie@1: 'js/comments.js', gremmie@1: 'js/markitup/jquery.markitup.pack.js', gremmie@1: 'js/markitup/sets/markdown/set.js', gremmie@1: )