Ticket #10680: comments-doc-10278.diff

File comments-doc-10278.diff, 7.4 KB (added by jakub_vysoky, 16 years ago)

BaseCommentAbstractForm for contrib.comments

  • django/contrib/comments/forms.py

    diff --git a/django/contrib/comments/forms.py b/django/contrib/comments/forms.py
    index 4ba12ef..f256f5d 100644
    a b from django import forms  
    55from django.forms.util import ErrorDict
    66from django.conf import settings
    77from django.contrib.contenttypes.models import ContentType
    8 from models import Comment
    98from django.utils.encoding import force_unicode
    109from django.utils.hashcompat import sha_constructor
    1110from django.utils.text import get_text_list
    1211from django.utils.translation import ungettext, ugettext_lazy as _
     12from django.contrib.comments.models import Comment, BaseCommentAbstractModel
    1313
    1414COMMENT_MAX_LENGTH = getattr(settings,'COMMENT_MAX_LENGTH', 3000)
    1515
    class CommentSecurityForm(forms.Form):  
    2828            initial = {}
    2929        initial.update(self.generate_security_data())
    3030        super(CommentSecurityForm, self).__init__(data=data, initial=initial)
    31        
     31
    3232    def security_errors(self):
    3333        """Return just those errors associated with security"""
    3434        errors = ErrorDict()
    class CommentSecurityForm(forms.Form):  
    8686        info = (content_type, object_pk, timestamp, settings.SECRET_KEY)
    8787        return sha_constructor("".join(info)).hexdigest()
    8888
    89 class CommentDetailsForm(CommentSecurityForm):
     89class BaseCommentAbstractForm(CommentSecurityForm):
    9090    """
    91     Handles the specific details of the comment (name, comment, etc.).
     91    Form for the BaseCommentAbstractModel.
    9292    """
    93     name          = forms.CharField(label=_("Name"), max_length=50)
    94     email         = forms.EmailField(label=_("Email address"))
    95     url           = forms.URLField(label=_("URL"), required=False)
    96     comment       = forms.CharField(label=_('Comment'), widget=forms.Textarea,
    97                                     max_length=COMMENT_MAX_LENGTH)
    98 
    9993    def get_comment_object(self):
    10094        """
    10195        Return a new (unsaved) comment object based on the information in this
    class CommentDetailsForm(CommentSecurityForm):  
    107101        """
    108102        if not self.is_valid():
    109103            raise ValueError("get_comment_object may only be called on valid forms")
    110        
     104
    111105        CommentModel = self.get_comment_model()
    112106        new = CommentModel(**self.get_comment_create_data())
    113107        new = self.check_for_duplicate_comment(new)
    114        
     108
    115109        return new
    116        
     110
    117111    def get_comment_model(self):
    118112        """
    119113        Get the comment model to create with this form. Subclasses in custom
    120114        comment apps should override this, get_comment_create_data, and perhaps
    121115        check_for_duplicate_comment to provide custom comment models.
    122116        """
    123         return Comment
    124        
     117        return BaseCommentAbstractModel
     118
    125119    def get_comment_create_data(self):
    126120        """
    127121        Returns the dict of data to be used to create a comment. Subclasses in
    class CommentDetailsForm(CommentSecurityForm):  
    131125        return dict(
    132126            content_type = ContentType.objects.get_for_model(self.target_object),
    133127            object_pk    = force_unicode(self.target_object._get_pk_val()),
     128            site_id      = settings.SITE_ID,
     129        )
     130
     131    def check_for_duplicate_comment(self, new):
     132        """
     133        This meant to be overriden in custom form.
     134        Do any checks that this comment is not a duplicate here.
     135        """
     136        return new
     137
     138class CommentDetailsForm(BaseCommentAbstractForm):
     139    """
     140    Handles the specific details of the comment (name, comment, etc.).
     141    """
     142    name          = forms.CharField(label=_("Name"), max_length=50)
     143    email         = forms.EmailField(label=_("Email address"))
     144    url           = forms.URLField(label=_("URL"), required=False)
     145    comment       = forms.CharField(label=_('Comment'), widget=forms.Textarea,
     146                                    max_length=COMMENT_MAX_LENGTH)
     147
     148    def get_comment_model(self):
     149        return Comment
     150
     151    def get_comment_create_data(self):
     152        data = super(CommentDetailsForm, self).get_comment_create_data()
     153        data.update(dict(
    134154            user_name    = self.cleaned_data["name"],
    135155            user_email   = self.cleaned_data["email"],
    136156            user_url     = self.cleaned_data["url"],
    137157            comment      = self.cleaned_data["comment"],
    138158            submit_date  = datetime.datetime.now(),
    139             site_id      = settings.SITE_ID,
    140159            is_public    = True,
    141160            is_removed   = False,
    142         )
    143        
     161        ))
     162        return data
     163
    144164    def check_for_duplicate_comment(self, new):
    145165        """
    146166        Check that a submitted comment isn't a duplicate. This might be caused
    class CommentDetailsForm(CommentSecurityForm):  
    156176        for old in possible_duplicates:
    157177            if old.submit_date.date() == new.submit_date.date() and old.comment == new.comment:
    158178                return old
    159                
     179
    160180        return new
    161181
    162182    def clean_comment(self):
  • django/contrib/comments/models.py

    diff --git a/django/contrib/comments/models.py b/django/contrib/comments/models.py
    index 56642b2..08097a0 100644
    a b class BaseCommentAbstractModel(models.Model):  
    2424    content_object = generic.GenericForeignKey(ct_field="content_type", fk_field="object_pk")
    2525
    2626    # Metadata about the comment
    27     site        = models.ForeignKey(Site)
     27    site        = models.ForeignKey(Site) # backward compatibility stuff
    2828
    2929    class Meta:
    3030        abstract = True
  • docs/ref/contrib/comments/custom.txt

    diff --git a/docs/ref/contrib/comments/custom.txt b/docs/ref/contrib/comments/custom.txt
    index d4b1756..2952663 100644
    a b In the ``models.py`` we'll define a ``CommentWithTitle`` model::  
    6969        title = models.CharField(max_length=300)
    7070   
    7171All custom comment models must subclass :class:`BaseCommentAbstractModel`.
     72Or if you just want to add title field to a comment, extend :class:`Comment`.
    7273
    7374Next, we'll define a custom comment form in ``forms.py``. This is a little more
    7475tricky: we have to both create a form and override
    tricky: we have to both create a form and override  
    7778field::
    7879
    7980    from django import forms
    80     from django.contrib.comments.forms import CommentForm
     81    from django.contrib.comments.forms import BaseCommentAbstractForm
    8182    from my_comment_app.models import CommentWithTitle
    8283
    83     class CommentFormWithTitle(CommentForm):
     84    class CommentFormWithTitle(BaseCommentAbstractForm):
    8485        title = forms.CharField(max_length=300)
    8586       
    8687        def get_comment_model(self):
    more.  
    100101Finally, we'll define a couple of methods in ``my_custom_app/__init__.py`` to
    101102point Django at these classes we've created::
    102103
    103     from my_comments_app.models import CommentWithTitle
    104     from my_comments_app.forms import CommentFormWithTitle
     104    from my_comment_app.models import CommentWithTitle
     105    from my_comment_app.forms import CommentFormWithTitle
    105106
    106107    def get_model():
    107108        return CommentWithTitle
    however.  
    186187    Return the URL for the "approve this comment from moderation" view.
    187188
    188189    The default implementation returns a reverse-resolved URL pointing
    189     to the :func:`django.contrib.comments.views.moderation.approve` view.
    190  No newline at end of file
     190    to the :func:`django.contrib.comments.views.moderation.approve` view.
Back to Top