Code

Ticket #10680: comments-doc-10278.diff

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

BaseCommentAbstractForm for contrib.comments

Line 
1diff --git a/django/contrib/comments/forms.py b/django/contrib/comments/forms.py
2index 4ba12ef..f256f5d 100644
3--- a/django/contrib/comments/forms.py
4+++ b/django/contrib/comments/forms.py
5@@ -5,11 +5,11 @@ from django import forms
6 from django.forms.util import ErrorDict
7 from django.conf import settings
8 from django.contrib.contenttypes.models import ContentType
9-from models import Comment
10 from django.utils.encoding import force_unicode
11 from django.utils.hashcompat import sha_constructor
12 from django.utils.text import get_text_list
13 from django.utils.translation import ungettext, ugettext_lazy as _
14+from django.contrib.comments.models import Comment, BaseCommentAbstractModel
15 
16 COMMENT_MAX_LENGTH = getattr(settings,'COMMENT_MAX_LENGTH', 3000)
17 
18@@ -28,7 +28,7 @@ class CommentSecurityForm(forms.Form):
19             initial = {}
20         initial.update(self.generate_security_data())
21         super(CommentSecurityForm, self).__init__(data=data, initial=initial)
22-       
23+
24     def security_errors(self):
25         """Return just those errors associated with security"""
26         errors = ErrorDict()
27@@ -86,16 +86,10 @@ class CommentSecurityForm(forms.Form):
28         info = (content_type, object_pk, timestamp, settings.SECRET_KEY)
29         return sha_constructor("".join(info)).hexdigest()
30 
31-class CommentDetailsForm(CommentSecurityForm):
32+class BaseCommentAbstractForm(CommentSecurityForm):
33     """
34-    Handles the specific details of the comment (name, comment, etc.).
35+    Form for the BaseCommentAbstractModel.
36     """
37-    name          = forms.CharField(label=_("Name"), max_length=50)
38-    email         = forms.EmailField(label=_("Email address"))
39-    url           = forms.URLField(label=_("URL"), required=False)
40-    comment       = forms.CharField(label=_('Comment'), widget=forms.Textarea,
41-                                    max_length=COMMENT_MAX_LENGTH)
42-
43     def get_comment_object(self):
44         """
45         Return a new (unsaved) comment object based on the information in this
46@@ -107,21 +101,21 @@ class CommentDetailsForm(CommentSecurityForm):
47         """
48         if not self.is_valid():
49             raise ValueError("get_comment_object may only be called on valid forms")
50-       
51+
52         CommentModel = self.get_comment_model()
53         new = CommentModel(**self.get_comment_create_data())
54         new = self.check_for_duplicate_comment(new)
55-       
56+
57         return new
58-       
59+
60     def get_comment_model(self):
61         """
62         Get the comment model to create with this form. Subclasses in custom
63         comment apps should override this, get_comment_create_data, and perhaps
64         check_for_duplicate_comment to provide custom comment models.
65         """
66-        return Comment
67-       
68+        return BaseCommentAbstractModel
69+
70     def get_comment_create_data(self):
71         """
72         Returns the dict of data to be used to create a comment. Subclasses in
73@@ -131,16 +125,42 @@ class CommentDetailsForm(CommentSecurityForm):
74         return dict(
75             content_type = ContentType.objects.get_for_model(self.target_object),
76             object_pk    = force_unicode(self.target_object._get_pk_val()),
77+            site_id      = settings.SITE_ID,
78+        )
79+
80+    def check_for_duplicate_comment(self, new):
81+        """
82+        This meant to be overriden in custom form.
83+        Do any checks that this comment is not a duplicate here.
84+        """
85+        return new
86+
87+class CommentDetailsForm(BaseCommentAbstractForm):
88+    """
89+    Handles the specific details of the comment (name, comment, etc.).
90+    """
91+    name          = forms.CharField(label=_("Name"), max_length=50)
92+    email         = forms.EmailField(label=_("Email address"))
93+    url           = forms.URLField(label=_("URL"), required=False)
94+    comment       = forms.CharField(label=_('Comment'), widget=forms.Textarea,
95+                                    max_length=COMMENT_MAX_LENGTH)
96+
97+    def get_comment_model(self):
98+        return Comment
99+
100+    def get_comment_create_data(self):
101+        data = super(CommentDetailsForm, self).get_comment_create_data()
102+        data.update(dict(
103             user_name    = self.cleaned_data["name"],
104             user_email   = self.cleaned_data["email"],
105             user_url     = self.cleaned_data["url"],
106             comment      = self.cleaned_data["comment"],
107             submit_date  = datetime.datetime.now(),
108-            site_id      = settings.SITE_ID,
109             is_public    = True,
110             is_removed   = False,
111-        )
112-       
113+        ))
114+        return data
115+
116     def check_for_duplicate_comment(self, new):
117         """
118         Check that a submitted comment isn't a duplicate. This might be caused
119@@ -156,7 +176,7 @@ class CommentDetailsForm(CommentSecurityForm):
120         for old in possible_duplicates:
121             if old.submit_date.date() == new.submit_date.date() and old.comment == new.comment:
122                 return old
123-               
124+
125         return new
126 
127     def clean_comment(self):
128diff --git a/django/contrib/comments/models.py b/django/contrib/comments/models.py
129index 56642b2..08097a0 100644
130--- a/django/contrib/comments/models.py
131+++ b/django/contrib/comments/models.py
132@@ -24,7 +24,7 @@ class BaseCommentAbstractModel(models.Model):
133     content_object = generic.GenericForeignKey(ct_field="content_type", fk_field="object_pk")
134 
135     # Metadata about the comment
136-    site        = models.ForeignKey(Site)
137+    site        = models.ForeignKey(Site) # backward compatibility stuff
138 
139     class Meta:
140         abstract = True
141diff --git a/docs/ref/contrib/comments/custom.txt b/docs/ref/contrib/comments/custom.txt
142index d4b1756..2952663 100644
143--- a/docs/ref/contrib/comments/custom.txt
144+++ b/docs/ref/contrib/comments/custom.txt
145@@ -69,6 +69,7 @@ In the ``models.py`` we'll define a ``CommentWithTitle`` model::
146         title = models.CharField(max_length=300)
147     
148 All custom comment models must subclass :class:`BaseCommentAbstractModel`.
149+Or if you just want to add title field to a comment, extend :class:`Comment`.
150 
151 Next, we'll define a custom comment form in ``forms.py``. This is a little more
152 tricky: we have to both create a form and override
153@@ -77,10 +78,10 @@ tricky: we have to both create a form and override
154 field::
155 
156     from django import forms
157-    from django.contrib.comments.forms import CommentForm
158+    from django.contrib.comments.forms import BaseCommentAbstractForm
159     from my_comment_app.models import CommentWithTitle
160 
161-    class CommentFormWithTitle(CommentForm):
162+    class CommentFormWithTitle(BaseCommentAbstractForm):
163         title = forms.CharField(max_length=300)
164         
165         def get_comment_model(self):
166@@ -100,8 +101,8 @@ more.
167 Finally, we'll define a couple of methods in ``my_custom_app/__init__.py`` to
168 point Django at these classes we've created::
169 
170-    from my_comments_app.models import CommentWithTitle
171-    from my_comments_app.forms import CommentFormWithTitle
172+    from my_comment_app.models import CommentWithTitle
173+    from my_comment_app.forms import CommentFormWithTitle
174 
175     def get_model():
176         return CommentWithTitle
177@@ -186,4 +187,4 @@ however.
178     Return the URL for the "approve this comment from moderation" view.
179 
180     The default implementation returns a reverse-resolved URL pointing
181-    to the :func:`django.contrib.comments.views.moderation.approve` view.
182\ No newline at end of file
183+    to the :func:`django.contrib.comments.views.moderation.approve` view.