示例#1
0
def edit_my_comment(request, comment_id):
    if not request.user.is_authenticated():
        return HttpResponse(status=401)

    if not (request.method == 'POST' and \
            request.is_ajax()):
        raise Http404

    response = {}
    post_data = request.POST.copy()
    ctype = post_data.get("content_type")
    object_pk = post_data.get("object_pk")

    if ctype is None or object_pk is None:
        raise Exception('Missing content_type or object_pk fields')

    try:
        model = models.get_model(*ctype.split(".", 1))
        target = model._default_manager.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), e:
        return CommentPostBadRequest(
            "Attempting go get content-type %r and object PK %r exists raised %s" % \
                (escape(ctype), escape(object_pk), e.__class__.__name__))
示例#2
0
def post_block_comment(request, using=None):
    data = request.POST.copy()  # Copy, otherwise QueryDict is immutable

    # Fill out some initial data fields from an authenticated user, if present
    if request.user.is_authenticated():
        if not data.get('name', ''):
            data["name"] = request.user.get_full_name(
            ) or request.user.username
        if not data.get('email', ''):
            data["email"] = request.user.email

    # ContentType validation
    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), e:
        return CommentPostBadRequest(
            "Attempting go get content-type %r and object PK %r exists raised %s" % \
                (escape(ctype), escape(object_pk), e.__class__.__name__))
示例#3
0
文件: views.py 项目: kstastny/edesia
def __get_form(request):
    """
    Validates and returns the form. Modified post_comment from 
    django.contrib.comments.views.comments
    """
    # 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.username
        if not data.get('email', ''):
            data["email"] = request.user.email

    # Check to see if the POST data overrides the view's next argument.
    #next = data.get("next", next) #not necessary

    # 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.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)))

    # 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())))

    return form
示例#4
0
def new_comment(request, comment_id=None, *args, **kwargs):
    
    is_ajax = request.GET.get('is_ajax') and '_ajax' or ''
    
    if not comment_id:
        return CommentPostBadRequest("Missing comment id.")
        
    parent_comment = get_model().objects.get(pk=comment_id)
    
    target = parent_comment.content_object
    model = target.__class__
    
    # Construct the initial comment form
    form = get_form()(target, parent_comment=parent_comment)
        
    template_list = [
        "comments/%s_%s_new_form%s.html" % tuple(str(model._meta).split(".") + [is_ajax]),
        "comments/%s_new_form%s.html" % (model._meta.app_label, is_ajax),
        "comments/new_form%s.html" % is_ajax,
    ]
    return render_to_response(
        template_list, {
            "form" : form,
        }, 
        RequestContext(request, {})
    )
示例#5
0
def post_comment_ajax(request, using=None):
    """
    Post a comment, via an Ajax call.
    """
    if not request.is_ajax():
        return HttpResponseBadRequest("Expecting Ajax call")

    # This is copied from django.contrib.comments.
    # Basically that view does too much, and doesn't offer a hook to change the rendering.
    # The request object is not passed to next_redirect for example.
    #
    # This is a separate view to integrate both features. Previously this used django-ajaxcomments
    # which is unfortunately not thread-safe (it it changes the comment view per request).

    # 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.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: {0!r}".format)
    except AttributeError:
        return CommentPostBadRequest(
            "The given content-type {0} does not resolve to a valid model.".
            format)
    except ObjectDoesNotExist:
        return CommentPostBadRequest(
            "No object matching content-type {0} and object PK {1} exists.".
            format(escape(ctype), escape(object_pk)))
    except (ValueError, ValidationError), e:
        return CommentPostBadRequest(
            "Attempting go get content-type {0!r} and object PK {1!r} exists raised {2}"
            .format(escape(ctype), escape(object_pk), e.__class__.__name__))
示例#6
0
文件: views.py 项目: ng/tbonline
def verify_comment(request, next=None, using=None):
    """
    Verify a comment. A ReCaptcha will be shown for verification.

    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.username
        if not data.get('email', ''):
            data["email"] = request.user.email

    # Check to see if the POST data overrides the view's next argument.
    next = data.get("next", next)

    # 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), e:
        return CommentPostBadRequest(
            "Attempting go get content-type %r and object PK %r exists raised %s" % \
                (escape(ctype), escape(object_pk), e.__class__.__name__))
示例#7
0
    def _save_comment(self, job):
        data = self.request.POST.copy()
        if self.request.user.is_authenticated():
            if not data.get('name', ''):
                data['name'] = self.request.user.get_full_name(
                ) or self.request.user.get_username()
            if not data.get('email', ''):
                data['email'] = self.request.user.email

        form = comments.get_form()(job, data=data)
        if form.security_errors():
            return CommentPostBadRequest(
                "The comment form failed security verification: %s" % \
                    escape(str(form.security_errors())))
        if form.errors:
            return CommentPostBadRequest(
                "Validation error in comment: %s" % \
                    escape(str(form.errors)))

        comment = form.get_comment_object()
        comment.ip_address = self.request.META.get("REMOTE_ADDR", None)
        comment.user = self.request.user

        # Signal that the comment is about to be saved
        responses = signals.comment_will_be_posted.send(
            sender=comment.__class__, comment=comment, request=self.request)

        for (receiver, response) in responses:
            if response == 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=self.request)
        return True
示例#8
0
文件: views.py 项目: ng/tbonline
def post_comment(request, next=None, using=None):
    form = RecaptchaForm(request.POST)
    data = request.session['data']
    model = request.session['model']
    target = request.session['target']
    next = data.get("next", next)
    if form.is_valid():
        form = comments.get_form()(target, data=data)
        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__)

        # Save the comment and signal that it was saved
        comment.save()
        signals.comment_was_posted.send(sender=comment.__class__,
                                        comment=comment,
                                        request=request)
        return next_redirect(data, next, comment_done, c=comment._get_pk_val())
    else:
        template_list = [
            "comments/%s_%s_verify.html" %
            (model._meta.app_label, model._meta.module_name),
            "comments/%s_verify.html" % model._meta.app_label,
            "comments/%s/%s/verify.html" %
            (model._meta.app_label, model._meta.module_name),
            "comments/%s/verify.html" % model._meta.app_label,
            "comments/verify.html",
        ]
        return render_to_response(
            template_list, {
                "comment": request.session['data'].get("comment", ""),
                "form": form,
                "next": next,
            }, RequestContext(request, {}))
示例#9
0
            "No object matching content-type {0} and object PK {1} exists.".
            format(escape(ctype), escape(object_pk)))
    except (ValueError, ValidationError), e:
        return CommentPostBadRequest(
            "Attempting go get content-type {0!r} and object PK {1!r} exists raised {2}"
            .format(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: {0}".format)

    # If there are errors or if we requested a preview show the comment
    if preview:
        comment = form.get_comment_object() if not form.errors else None
        return _ajax_result(request, form, "preview", comment)
    if form.errors:
        return _ajax_result(request, form, "post")

    # 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
示例#10
0
def post_comment(request, using=None):
    """
    This method is written with reference to
    django.contrib.comments.views.comments.post_comment() to make compatible with Ajax calls
    """
    if not request.user.is_authenticated():
        return HttpResponse('Unauthorized', status=401)

    if request.is_ajax():

        # response JSON object
        response = {'success': False}

        # Fill out some initial data fields from an authenticated user, if present
        data = request.POST.copy()
        data["name"] = request.user.get_full_name() or request.user.username
        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), e:
            return CommentPostBadRequest(
                "Attempting go get content-type %r and object PK %r exists raised %s" % \
                    (escape(ctype), escape(object_pk), e.__class__.__name__))

        # 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 form.errors:
            return HttpResponse(simplejson.dumps(response),
                                mimetype="application/json")

        # Otherwise create the comment
        comment = form.get_comment_object()
        comment.ip_address = request.META.get("REMOTE_ADDR", None)
        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__)

        # Save the comment and signal that it was saved
        comment.save()
        signals.comment_was_posted.send(sender=comment.__class__,
                                        comment=comment,
                                        request=request)

        # get updated comments count on object
        comments_count = comments.get_model().objects.filter(
            content_type=comment.content_type,
            object_pk=object_pk).exclude(is_removed=True).count()
        response['comments_count'] = comments_count

        response['success'] = True
        return HttpResponse(simplejson.dumps(response),
                            mimetype="application/json")
示例#11
0
        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), e:
        return CommentPostBadRequest(
            "Attempting go get content-type %r and object PK %r exists raised %s" % \
                (escape(ctype), escape(object_pk), e.__class__.__name__))

    form = SpcCommentEditForm(target, data=request.POST)
    if form.security_errors():
        return CommentPostBadRequest(
                "The comment edit form failed security verification: %s" % \
                    escape(str(form.security_errors())))

    form = form.cleaned_data

    comment = get_object_or_404(comments.get_model(),
                                pk=comment_id,
                                site__pk=settings.SITE_ID)
    if comment.user == request.user:
        comment.comment = form['edit_comment']
        comment.rest_comment = compile_rest_to_html(form['edit_comment'])
        comment.ip_address = request.META.get('REMOTE_ADDR', None)
        comment.save()

        response['comment'] = comment.comment
        response['rest_comment'] = comment.rest_comment
示例#12
0
def post(request, next=None, using=None):

    if request.method == 'POST':

        # Fill out some initial data fields from an authenticated user, if present
        data = request.POST.copy()
        comments_type = data.get('comments_type', 'comments')

        if request.user.is_authenticated():
            if not data.get('name', ''):
                data['name'] = request.user.get_full_name(
                ) or request.user.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), e:
            return CommentPostBadRequest(
                "Attempting go get content-type %r and object PK %r exists raised %s" % \
                    (escape(ctype), escape(object_pk), e.__class__.__name__))

        # Construct the comment form
        CommentForm = get_comment_form(data['formclass'])
        form = CommentForm(target, comments_type=comments_type, 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:
            # handle errors or preview
            pass

        # 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__)

        # Save the comment and signal that it was saved
        comment.save()
        signals.comment_was_posted.send(sender=comment.__class__,
                                        comment=comment,
                                        request=request)

        comments = Comment.objects.filter(pk=comment.pk)
        comments = comments.select_related('user')
        comments = comments.prefetch_related('children__user', 'likes')
        comment = comments[0]
        comment.set_comment_template_dir(comments_type)
示例#13
0
文件: views.py 项目: whit/ella
def post_comment(request, context, parent_id=None):
    'Mostly copy-pasted from django.contrib.comments.views.comments'
    opts = CommentOptionsObject.objects.get_for_object(context['object'])
    if opts.blocked:
        raise Http404('Comments are blocked for this object.')
    context['opts'] = opts

    parent = None
    if parent_id:
        parent = get_object_or_404(comments.get_model(), pk=parent_id)

    ip_address = request.META.get('REMOTE_ADDR', None)
    try:
        ip_ban = BannedIP.objects.get(ip_address=ip_address)
    except BannedIP.DoesNotExist:
        ip_ban = None

    if request.method != 'POST' or ip_ban:
        initial = {}
        if parent:
            if parent.title.startswith('Re:'):
                initial['title'] = parent.title
            else:
                initial['title'] = u'Re: %s' % parent.title
        form = comments.get_form()(context['object'],
                                   parent=parent_id,
                                   initial=initial)
        context.update({
            'parent': parent,
            'form': form,
            'ip_ban': ip_ban,
        })
        return render_to_response(
            get_templates_from_placement('comment_form.html',
                                         context['placement']), context,
            RequestContext(request))

    # 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.username
        if not data.get('email', ''):
            data["email"] = request.user.email

    # construct the form
    form = comments.get_form()(context['object'], data=data, parent=parent_id)

    # Check security information
    if form.security_errors():
        return CommentPostBadRequest(
            "The comment form failed security verification: %s" % \
                escape(str(form.security_errors())))

    # Do we want to preview the comment?
    preview = "preview" in data

    # Check to see if the POST data overrides the view's next argument.
    next = data.get(
        "next", "%s%s/" %
        (context['placement'].get_absolute_url(), slugify(_('comments'))))

    # If there are errors or if we requested a preview show the comment
    if form.errors or preview:
        context.update({
            "form": form,
            'parent': parent,
            "next": next,
        })
        return render_to_response(
            get_templates_from_placement(
                form.errors and 'comment_form.html' or 'comment_preview.html',
                context['placement']), context, 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 opts.premoderated:
        comment.is_public = False

    # Save the comment and signal that it was saved
    comment.save()
    signals.comment_was_posted.send(sender=comment.__class__,
                                    comment=comment,
                                    request=request)

    return HttpResponseRedirect(next)
def post_comment_ajax(request, using=None):
    """
    Post a comment, via an Ajax call.
    """
    if not request.is_ajax():
        return HttpResponseBadRequest("Expecting Ajax call")

    # This is copied from django.contrib.comments.
    # Basically that view does too much, and doesn't offer a hook to change the rendering.
    # The request object is not passed to next_redirect for example.
    #
    # This is a separate view to integrate both features. Previously this used django-ajaxcomments
    # which is unfortunately not thread-safe (it it changes the comment view per request).

    # 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.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 ValueError:
        return CommentPostBadRequest("Invalid object_pk value: {0}".format(
            escape(object_pk)))
    except TypeError:
        return CommentPostBadRequest("Invalid content_type value: {0}".format(
            escape(ctype)))
    except AttributeError:
        return CommentPostBadRequest(
            "The given content-type {0} does not resolve to a valid model.".
            format(escape(ctype)))
    except ObjectDoesNotExist:
        return CommentPostBadRequest(
            "No object matching content-type {0} and object PK {1} exists.".
            format(escape(ctype), escape(object_pk)))
    except (ValueError, ValidationError) as e:
        return CommentPostBadRequest(
            "Attempting go get content-type {0!r} and object PK {1!r} exists raised {2}"
            .format(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: {0}".format)

    # If there are errors or if we requested a preview show the comment
    if preview:
        comment = form.get_comment_object() if not form.errors else None
        return _ajax_result(request,
                            form,
                            "preview",
                            comment,
                            object_id=object_pk)
    if form.errors:
        return _ajax_result(request, form, "post", object_id=object_pk)

    # 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 {0} killed the comment".
                format(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)

    return _ajax_result(request, form, "post", comment, object_id=object_pk)
示例#15
0
def post_comment(request, next=None, *args, **kwargs):
    """
    Post a comment.

    HTTP POST is required unless a initial form is requested. If ``POST['submit'] == "preview"`` or if there are
    errors a preview template, ``comments/preview.html``, will be rendered.
    """

    # Require POST
    if request.method != 'POST':
        return http.HttpResponseNotAllowed(["POST"])
        
    is_ajax = request.POST.get('is_ajax') and '_ajax' or ''

    # 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()
        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")
    parent_pk = data.get("parent_pk")
    parent_comment = None
    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.get(pk=object_pk)
        if parent_pk:
            parent_comment = get_model().objects.get(pk=parent_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 MpttComment.DoesNotExist:
        return CommentPostBadRequest(
            "Parent comment with PK %r does not exist." % \
                escape(parent_pk))
    except ObjectDoesNotExist:
        return CommentPostBadRequest(
            "No object matching content-type %r and object PK %r exists." % \
                (escape(ctype), escape(object_pk)))

    # Do we want to preview the comment?
    preview = data.get("submit", "").lower() == "preview" or \
              data.get("preview", None) is not None
        
    # Construct the comment form 
    form = get_form()(target, parent_comment=parent_comment, 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 = [
            "comments/%s_%s_preview%s.html" % tuple(str(model._meta).split(".") + [is_ajax]),
            "comments/%s_preview%s.html" % (model._meta.app_label, is_ajax),
            "comments/preview%s.html" % is_ajax
        ]
        return render_to_response(
            template_list, {
                "comment" : form.data.get("comment", ""),
                "title" : form.data.get("title", ""),
                "form" : form,
                "allow_post": not form.errors,
                "is_ajax" : is_ajax
            }, 
            RequestContext(request, {})
        )

    # Otherwise create the comment
    comment = form.get_comment_object()
    comment.ip_address = get_ip(request)
    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__)

    # Save the comment and signal that it was saved
    comment.save()
    signals.comment_was_posted.send(
        sender  = comment.__class__,
        comment = comment,
        request = request
    )
    
    return next_redirect(data, next, 'comments-comment-done%s' % (is_ajax and '-ajax' or ''), c=comment._get_pk_val())