Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

a more consistent way to implement a custom comment form #5

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
79 changes: 35 additions & 44 deletions mptt_comments/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,21 @@
from django.conf import settings
from django.contrib.comments import get_model
from django.contrib.comments.forms import CommentForm
from django.contrib.comments.models import Comment
from django.contrib.contenttypes.models import ContentType
from django.utils.translation import ugettext_lazy as _
from django import forms
import time
import datetime
from mptt_comments.models import MpttComment

class MpttCommentForm(CommentForm):
title = forms.CharField(label=_("Title"))
parent_pk = forms.IntegerField(widget=forms.HiddenInput, required=False)

def __init__(self, target_object, parent_comment=None, data=None, initial=None):
self.parent_comment = parent_comment
super(MpttCommentForm, self).__init__(target_object, data=data, initial=initial)
if self.should_title_be_forced():
self.fields['title'].widget.attrs['readonly'] = True

self.fields.keyOrder = [
'title',
'comment',
Expand All @@ -29,10 +27,10 @@ def __init__(self, target_object, parent_comment=None, data=None, initial=None):
'security_hash',
'parent_pk'
]

def should_title_be_forced(self):
return self.parent_comment and getattr(settings, 'MPTT_FORCE_TITLE_ON_REPLIES', False)

def generate_title(self):
if not self.parent_comment:
return force_unicode(self.target_object)
Expand All @@ -42,56 +40,49 @@ def generate_title(self):
def clean_title(self):
if self.should_title_be_forced():
self.cleaned_data['title'] = self.generate_title()

# Truncates title to 255 chrs to avoid integrity errors
return self.cleaned_data['title'][:255]

def get_comment_object(self):
def get_comment_model(self):
"""
Return a new (unsaved) comment object based on the information in this
form. Assumes that the form is already validated and will throw a
ValueError if not.
Get the comment model to create with this form. Subclasses in custom
comment apps should override this, get_comment_create_data, and perhaps
check_for_duplicate_comment to provide custom comment models.
"""
return MpttComment

Does not set any of the fields that would come from a Request object
(i.e. ``user`` or ``ip_address``).
def get_comment_create_data(self):
"""
Returns the dict of data to be used to create a comment. Subclasses in
custom comment apps that override get_comment_model can override this
method to add extra fields onto a custom comment model.
"""
if not self.is_valid():
raise ValueError("get_comment_object may only be called on valid forms")

data = super(MpttCommentForm, self).get_comment_create_data()
parent_comment = None
parent_pk = self.cleaned_data.get("parent_pk")
if parent_pk:
parent_comment = get_model().objects.get(pk=parent_pk)

new = get_model()(
content_type = ContentType.objects.get_for_model(self.target_object),
object_pk = force_unicode(self.target_object._get_pk_val()),
user_name = "", # self.cleaned_data["name"],
user_email = "", # self.cleaned_data["email"],
user_url = "", # self.cleaned_data["url"],
comment = self.cleaned_data["comment"],
submit_date = datetime.datetime.now(),
site_id = settings.SITE_ID,
is_public = parent_comment and parent_comment.is_public or True,
is_removed = False,
title = self.cleaned_data["title"],
parent = parent_comment
)
data.update({
'user_name': '',
'user_email': '',
'user_url': '',
'is_public': parent_comment and parent_comment.is_public or True,
'title': self.cleaned_data["title"],
'parent': parent_comment
})

# FIXME: maybe re-implement duplicate checking later

return new

def generate_security_data(self):
"""Generate a dict of security data for "initial" data."""
timestamp = int(time.time())
security_dict = {
'content_type' : str(self.target_object._meta),
'object_pk' : str(self.target_object._get_pk_val()),
'timestamp' : str(timestamp),
'security_hash' : self.initial_security_hash(timestamp),
'parent_pk' : self.parent_comment and str(self.parent_comment.pk) or '',
'title' : self.generate_title(),
}
security_dict = {
'content_type': str(self.target_object._meta),
'object_pk': str(self.target_object._get_pk_val()),
'timestamp': str(timestamp),
'security_hash': self.initial_security_hash(timestamp),
'parent_pk': self.parent_comment and str(self.parent_comment.pk) or '',
'title': self.generate_title(),
}

return security_dict