You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
55 lines
2.0 KiB
55 lines
2.0 KiB
# -*- coding: utf-8 -*-
|
|
|
|
from django.views.generic.edit import FormMixin
|
|
|
|
from functions.http import JsonResponse
|
|
from .forms import CommentForm
|
|
|
|
|
|
class CommentMixin(FormMixin):
|
|
form_class = CommentForm
|
|
|
|
def get_comment_form(self):
|
|
form_class = self.get_form_class()
|
|
form = self.get_form(form_class)
|
|
form._user = self.request.user
|
|
return form
|
|
|
|
def post(self, request, *args, **kwargs):
|
|
self.commentform = None
|
|
if request.method == 'POST' and request.is_ajax():
|
|
self.commentform = self.get_comment_form()
|
|
if self.commentform.is_valid():
|
|
self.object = self.get_object()
|
|
self.save_comment()
|
|
return JsonResponse({'success': True})
|
|
else:
|
|
return JsonResponse({'success': False, 'errors': self.commentform.errors})
|
|
return self.get(request, *args, **kwargs)
|
|
|
|
def save_comment(self):
|
|
comment = self.commentform.save(commit=False)
|
|
comment.user_id = self.request.user.pk
|
|
comment.content_object = self.object
|
|
comment.ip = self.request.META['REMOTE_ADDR']
|
|
comment.save()
|
|
|
|
def get_context_data(self, **kwargs):
|
|
context = super(CommentMixin, self).get_context_data(**kwargs)
|
|
self.commentform = self.get_comment_form()
|
|
if self.request.method == 'POST' and self.commentform.is_valid():
|
|
self.save_comment()
|
|
context['commentform'] = self.commentform
|
|
_comments = list(self.object.comments.filter(hidden=False))
|
|
comments = {x.pk: x for x in filter(lambda x: x.parent is None, _comments)}
|
|
for comment in filter(lambda x: x.parent is not None, _comments):
|
|
try:
|
|
p = comments[comment.parent_id]
|
|
if hasattr(p, 'childs'):
|
|
p.childs.append(comment)
|
|
else:
|
|
p.childs = [comment]
|
|
except IndexError:
|
|
pass
|
|
context['comments'] = comments.values()
|
|
return context
|
|
|