Ticket #9958: comments.diff

File comments.diff, 5.8 KB (added by arne, 16 years ago)
  • django/contrib/comments/forms.py

     
    77from django.conf import settings
    88from django.http import Http404
    99from django.contrib.contenttypes.models import ContentType
    10 from models import Comment
     10from django.contrib import comments
    1111from django.utils.encoding import force_unicode
    1212from django.utils.hashcompat import sha_constructor
    1313from django.utils.text import get_text_list
     
    1515
    1616COMMENT_MAX_LENGTH = getattr(settings,'COMMENT_MAX_LENGTH', 3000)
    1717
    18 class CommentForm(forms.Form):
    19     name          = forms.CharField(label=_("Name"), max_length=50)
    20     email         = forms.EmailField(label=_("Email address"))
    21     url           = forms.URLField(label=_("URL"), required=False)
    22     comment       = forms.CharField(label=_('Comment'), widget=forms.Textarea,
    23                                     max_length=COMMENT_MAX_LENGTH)
     18class BaseCommentForm(forms.Form):
    2419    honeypot      = forms.CharField(required=False,
    2520                                    label=_('If you enter anything in this field '\
    2621                                            'your comment will be treated as spam'))
     
    3429        if initial is None:
    3530            initial = {}
    3631        initial.update(self.generate_security_data())
    37         super(CommentForm, self).__init__(data=data, initial=initial)
     32        super(BaseCommentForm, self).__init__(data=data, initial=initial)
    3833
    3934    def get_comment_object(self):
    4035        """
    4136        Return a new (unsaved) comment object based on the information in this
    42         form. Assumes that the form is already validated and will throw a
    43         ValueError if not.
    44 
    45         Does not set any of the fields that would come from a Request object
    46         (i.e. ``user`` or ``ip_address``).
     37        form. Subclasses must implement this.
    4738        """
    48         if not self.is_valid():
    49             raise ValueError("get_comment_object may only be called on valid forms")
     39        raise NotImplementedError("subclasses must implement get_comment_object")
    5040
    51         new = Comment(
    52             content_type = ContentType.objects.get_for_model(self.target_object),
    53             object_pk    = force_unicode(self.target_object._get_pk_val()),
    54             user_name    = self.cleaned_data["name"],
    55             user_email   = self.cleaned_data["email"],
    56             user_url     = self.cleaned_data["url"],
    57             comment      = self.cleaned_data["comment"],
    58             submit_date  = datetime.datetime.now(),
    59             site_id      = settings.SITE_ID,
    60             is_public    = True,
    61             is_removed   = False,
    62         )
    63 
    64         # Check that this comment isn't duplicate. (Sometimes people post comments
    65         # twice by mistake.) If it is, fail silently by returning the old comment.
    66         possible_duplicates = Comment.objects.filter(
    67             content_type = new.content_type,
    68             object_pk = new.object_pk,
    69             user_name = new.user_name,
    70             user_email = new.user_email,
    71             user_url = new.user_url,
    72         )
    73         for old in possible_duplicates:
    74             if old.submit_date.date() == new.submit_date.date() and old.comment == new.comment:
    75                 return old
    76 
    77         return new
    78 
    7941    def security_errors(self):
    8042        """Return just those errors associated with security"""
    8143        errors = ErrorDict()
     
    155117        """Generate a (SHA1) security hash from the provided info."""
    156118        info = (content_type, object_pk, timestamp, settings.SECRET_KEY)
    157119        return sha_constructor("".join(info)).hexdigest()
     120
     121
     122class CommentForm(BaseCommentForm):
     123    name          = forms.CharField(label=_("Name"), max_length=50)
     124    email         = forms.EmailField(label=_("Email address"))
     125    url           = forms.URLField(label=_("URL"), required=False)
     126    comment       = forms.CharField(label=_('Comment'), widget=forms.Textarea,
     127                                    max_length=COMMENT_MAX_LENGTH)
     128
     129    def get_comment_object(self):
     130        """
     131        Return a new (unsaved) comment object based on the information in this
     132        form. Assumes that the form is already validated and will throw a
     133        ValueError if not.
     134
     135        Does not set any of the fields that would come from a Request object
     136        (i.e. ``user`` or ``ip_address``).
     137        """
     138        if not self.is_valid():
     139            raise ValueError("get_comment_object may only be called on valid forms")
     140       
     141        comment_model = comments.get_model()
     142       
     143        new = comment_model(
     144            content_type = ContentType.objects.get_for_model(self.target_object),
     145            object_pk    = force_unicode(self.target_object._get_pk_val()),
     146            user_name    = self.cleaned_data["name"],
     147            user_email   = self.cleaned_data["email"],
     148            user_url     = self.cleaned_data["url"],
     149            comment      = self.cleaned_data["comment"],
     150            submit_date  = datetime.datetime.now(),
     151            site_id      = settings.SITE_ID,
     152            is_public    = True,
     153            is_removed   = False,
     154        )
     155
     156        # Check that this comment isn't duplicate. (Sometimes people post comments
     157        # twice by mistake.) If it is, fail silently by returning the old comment.
     158        possible_duplicates = comment_model.objects.filter(
     159            content_type = new.content_type,
     160            object_pk = new.object_pk,
     161            user_name = new.user_name,
     162            user_email = new.user_email,
     163            user_url = new.user_url,
     164        )
     165        for old in possible_duplicates:
     166            if old.submit_date.date() == new.submit_date.date() and old.comment == new.comment:
     167                return old
     168
     169        return new
Back to Top