def get_form(self, context): obj = self.get_object(context) request = context.get('request') if obj: return comments.get_form()(target=obj, request=request) else: return None
def get_form(self, context): ctype, object_pk = self.get_target_ctype_pk(context) parent_id = None if self.parent: parent_id = self.parent.resolve(context, ignore_failures=True) if object_pk: return comments.get_form()( ctype.get_object_for_this_type(pk=object_pk), parent=parent_id) else: return None
def _post(self, request): data = request.POST.copy() ctype = data.get("content_type") object_pk = data.get("object_pk") user = request.user # FIXME: spike! data["name"] = user.username or "Unknown" data["email"] = user.email or "Unknown@mail" if ctype is None or object_pk is None: return self.json_form_error_context(_(u'Кажется, что-то пошло не так :(')) try: model = models.get_model(*ctype.split(".", 1)) target = model._default_manager.get(pk=object_pk) except (TypeError, AttributeError, ObjectDoesNotExist, ValueError, ValidationError): return self.json_form_error_context(_(u'Кажется, для этого материала нельзя добавлять комментарии :(')) # Construct the comment form form = comments.get_form()(target, data=data) # Check security information if form.security_errors(): # hacker ? return self.json_form_error_context(_(u'Кажется, что-то пошло не так. Ты хакер? :(')) if not request.user.can_action('add-comment'): return self.json_form_error_context(_(u'Вы не можете добавлять новые комментарии так часто. Попробуйте позже!')) if form.is_valid(): comment = form.get_comment_object() comment.user = user try: comment.save() except (DatabaseError, IntegrityError) as e: return self.json_form_error_context(_(u'Кажется, что-то пошло не так :(')) if not user.is_superuser: user.make_action('add-comment') if hasattr(target, 'add_comment_hook'): target.add_comment_hook(comment) return self.json_success_context() else: #assert False, form.errors return self.json_error_context(form.errors.items())
def post_comment(request, next=None, using=None): """ Post a comment. HTTP POST is required. If ``POST['submit'] == "preview"`` or if there are errors a preview template, ``comments/preview.html``, will be rendered. """ # Fill out some initial data fields from an authenticated user, if present if not allowed_to_comment(request.user): messages.error(request, "You can't send more than 20 comments in an hour") return redirect("home") data = request.POST.copy() if request.user.is_authenticated(): if not data.get('name', ''): data["name"] = request.user.get_full_name( ) or request.user.get_username() if not data.get('email', ''): data["email"] = request.user.email # Look up the object we're trying to comment about ctype = data.get("content_type") object_pk = data.get("object_pk") if ctype is None or object_pk is None: return CommentPostBadRequest( "Missing content_type or object_pk field.") try: model = models.get_model(*ctype.split(".", 1)) target = model._default_manager.using(using).get(pk=object_pk) except TypeError: return CommentPostBadRequest("Invalid content_type value: %r" % escape(ctype)) except AttributeError: return CommentPostBadRequest( "The given content-type %r does not resolve to a valid model." % escape(ctype)) except ObjectDoesNotExist: return CommentPostBadRequest( "No object matching content-type %r and object PK %r exists." % (escape(ctype), escape(object_pk))) except (ValueError, ValidationError) as e: return CommentPostBadRequest( "Attempting go get content-type %r and object PK %r exists raised %s" % (escape(ctype), escape(object_pk), e.__class__.__name__)) # Do we want to preview the comment? preview = "preview" in data # Construct the comment form form = comments.get_form()(target, data=data) # Check security information if form.security_errors(): return CommentPostBadRequest( "The comment form failed security verification: %s" % escape(str(form.security_errors()))) # If there are errors or if we requested a preview show the comment if form.errors or preview: template_list = [ # These first two exist for purely historical reasons. # Django v1.0 and v1.1 allowed the underscore format for # preview templates, so we have to preserve that format. "comments/%s_%s_preview.html" % (model._meta.app_label, model._meta.model_name), "comments/%s_preview.html" % model._meta.app_label, # Now the usual directory based template hierarchy. "comments/%s/%s/preview.html" % (model._meta.app_label, model._meta.model_name), "comments/%s/preview.html" % model._meta.app_label, "comments/preview.html", ] return render_to_response( template_list, { "comment": form.data.get("comment", ""), "form": form, "next": data.get("next", next), }, RequestContext(request, {})) # Otherwise create the comment comment = form.get_comment_object() comment.ip_address = request.META.get("REMOTE_ADDR", None) if request.user.is_authenticated(): comment.user = request.user # Signal that the comment is about to be saved responses = signals.comment_will_be_posted.send(sender=comment.__class__, comment=comment, request=request) for (receiver, response) in responses: if response is False: return CommentPostBadRequest( "comment_will_be_posted receiver %r killed the comment" % receiver.__name__) # Save the comment and signal that it was saved comment.save() signals.comment_was_posted.send(sender=comment.__class__, comment=comment, request=request) if 'next' in request.REQUEST: next = request.REQUEST['next'] elif hasattr(target, 'get_absolute_url'): if callable(getattr(target, 'get_absolute_url')): next = target.get_absolute_url() else: next = target.get_absolute_url else: raise AttributeError('Define get_absolute_url') return next_redirect(request, fallback=next or 'comments-comment-done', c=comment._get_pk_val())
def post_comment(request, next=None, using=None): """ Post a comment. HTTP POST is required. If ``POST['submit'] == "preview"`` or if there are errors a preview template, ``comments/preview.html``, will be rendered. """ # Fill out some initial data fields from an authenticated user, if present data = request.POST.copy() if request.user.is_authenticated(): if not data.get('name', ''): data["name"] = request.user.get_full_name() or request.user.get_username() if not data.get('email', ''): data["email"] = request.user.email serializer = CommentSerializer(data) # Look up the object we're trying to comment about ctype = data.get("content_type") object_pk = data.get("object_pk") if ctype is None or object_pk is None: return CommentPostBadRequest("Missing content_type or object_pk field.") try: model = models.get_model(*ctype.split(".", 1)) target = model._default_manager.using(using).get(pk=object_pk) except TypeError: return CommentPostBadRequest( "Invalid content_type value: %r" % escape(ctype)) except AttributeError: return CommentPostBadRequest( "The given content-type %r does not resolve to a valid model." % \ escape(ctype)) except ObjectDoesNotExist: return CommentPostBadRequest( "No object matching content-type %r and object PK %r exists." % \ (escape(ctype), escape(object_pk))) except (ValueError, ValidationError) as e: return CommentPostBadRequest( "Attempting go get content-type %r and object PK %r exists raised %s" % \ (escape(ctype), escape(object_pk), e.__class__.__name__)) # Do we want to preview the comment? preview = "preview" in data # Construct the comment form form = comments.get_form()(target, data=data) # Check security information if form.security_errors(): return CommentPostBadRequest( "The comment form failed security verification: %s" % \ escape(str(form.security_errors()))) # If there are errors or if we requested a preview show the comment ''' if form.errors or preview: template_list = [ # These first two exist for purely historical reasons. # Django v1.0 and v1.1 allowed the underscore format for # preview templates, so we have to preserve that format. "comments/%s_%s_preview.html" % (model._meta.app_label, model._meta.module_name), "comments/%s_preview.html" % model._meta.app_label, # Now the usual directory based template hierarchy. "comments/%s/%s/preview.html" % (model._meta.app_label, model._meta.module_name), "comments/%s/preview.html" % model._meta.app_label, "comments/preview.html", ] return render_to_response( template_list, { "comment": form.data.get("comment", ""), "form": form, "next": data.get("next", next), }, RequestContext(request, {}) ) ''' # Otherwise create the comment comment = form.get_comment_object() comment.ip_address = request.META.get("REMOTE_ADDR", None) if request.user.is_authenticated(): comment.user = request.user # Signal that the comment is about to be saved responses = signals.comment_will_be_posted.send( sender=comment.__class__, comment=comment, request=request ) for (receiver, response) in responses: if response == False: return CommentPostBadRequest( "comment_will_be_posted receiver %r killed the comment" % receiver.__name__) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) '''
def get_form(self, context): obj = self.get_object(context) if obj: return comments.get_form()(obj) else: return None
from django.template import RequestContext from django.template.response import TemplateResponse from django.http import Http404, HttpResponse, HttpResponseNotAllowed, HttpResponseRedirect from django.utils.encoding import force_text from django.utils.html import escape from django.views.decorators.csrf import csrf_protect from django.views.decorators.http import require_POST import comments from comments import signals from comments import utils from comments.views.utils import next_redirect, confirmation_view from comments.utils import CommentPostBadRequest COMMENT_MODEL = comments.get_model() COMMENT_FORM = comments.get_form() def view(request, comment_pk=None, *args, **kwargs): comment_url = utils.get_comment_url(comment_pk=comment_pk, request=request) if comment_url: return HttpResponseRedirect(comment_url) else: raise Http404 @csrf_protect def edit(request, comment_pk=None, parent_pk=None, content_type=None, object_pk=None, next=None, *args, **kwargs): """ Edit or create a comment. Displays and processes the comment model form If HTTP POST is present it processes and adds / edits comment.
def testGetForm(self): from custom_comments.forms import CustomCommentForm self.assertEqual(comments.get_form(), CustomCommentForm)
def testGetForm(self): self.assertEqual(comments.get_form(), CommentForm)
"The given content-type %r does not resolve to a valid model." % \ escape(ctype)) except ObjectDoesNotExist: return CommentPostBadRequest( "No object matching content-type %r and object PK %r exists." % \ (escape(ctype), escape(object_pk))) except (ValueError, ValidationError), e: return CommentPostBadRequest( "Attempting go get content-type %r and object PK %r exists raised %s" % \ (escape(ctype), escape(object_pk), e.__class__.__name__)) # Do we want to preview the comment? preview = "preview" in data # Construct the comment form form = comments.get_form()(target, data=data) # Check security information if form.security_errors(): return CommentPostBadRequest( "The comment form failed security verification: %s" % \ escape(str(form.security_errors()))) # If there are errors or if we requested a preview show the comment if form.errors or preview: template_list = [ # These first two exist for purely historical reasons. # Django v1.0 and v1.1 allowed the underscore format for # preview templates, so we have to preserve that format. "comments/%s_%s_preview.html" % (model._meta.app_label, model._meta.module_name), "comments/%s_preview.html" % model._meta.app_label,