Esempio n. 1
0
def approve(request, comment_id, next=None):
    """
    Approve a comment (that is, mark it as public and non-removed). Confirmation
    on GET, action on POST. Requires the "can moderate comments" permission.

    Templates: `comments/approve.html`,
    Context:
        comment
            the `comments.comment` object for approval
    """
    comment = get_object_or_404(comments.get_model(),
                                pk=comment_id,
                                site__pk=settings.SITE_ID)

    # Delete on POST
    if request.method == 'POST':
        # Flag the comment as approved.
        perform_approve(request, comment)
        return next_redirect(request, next, approve_done, c=comment.pk)

    # Render a form on GET
    else:
        return render_to_response('comments/approve.html', {
            'comment': comment,
            "next": next
        }, template.RequestContext(request))
def delete(request, comment_id, next=None):
    """
    Deletes a comment. Confirmation on GET, action on POST. Requires the "can
    moderate comments" permission.

    Templates: :template:`comments/delete.html`,
    Context:
        comment
            the flagged `comments.comment` object
    """
    comment = get_object_or_404(comments.get_model(), pk=comment_id, site__pk=settings.SITE_ID)

    # Delete on POST
    if request.method == 'POST':
        # Flag the comment as deleted instead of actually deleting it.
        perform_delete(request, comment)
        return next_redirect(request, fallback=next or 'comments-delete-done',
            c=comment.pk)

    # Render a form on GET
    else:
        return render_to_response('comments/delete.html',
            {'comment': comment, "next": next},
            template.RequestContext(request)
        )
Esempio n. 3
0
def delete(request, comment_id, next=None):
    """
    Deletes a comment. Confirmation on GET, action on POST. Requires the "can
    moderate comments" permission.

    Templates: `comments/delete.html`,
    Context:
        comment
            the flagged `comments.comment` object
    """
    comment = get_object_or_404(comments.get_model(),
                                pk=comment_id,
                                site__pk=settings.SITE_ID)

    # Delete on POST
    if request.method == 'POST':
        # Flag the comment as deleted instead of actually deleting it.
        perform_delete(request, comment)
        return next_redirect(request, next, delete_done, c=comment.pk)

    # Render a form on GET
    else:
        return render_to_response('comments/delete.html', {
            'comment': comment,
            "next": next
        }, template.RequestContext(request))
def approve(request, comment_id, next=None):
    """
    Approve a comment (that is, mark it as public and non-removed). Confirmation
    on GET, action on POST. Requires the "can moderate comments" permission.

    Templates: :template:`comments/approve.html`,
    Context:
        comment
            the `comments.comment` object for approval
    """
    comment = get_object_or_404(comments.get_model(), pk=comment_id, site__pk=settings.SITE_ID)

    # Delete on POST
    if request.method == 'POST':
        # Flag the comment as approved.
        perform_approve(request, comment)
        return next_redirect(request, fallback=next or 'comments-approve-done',
            c=comment.pk)

    # Render a form on GET
    else:
        return render_to_response('comments/approve.html',
            {'comment': comment, "next": next},
            template.RequestContext(request)
        )
def flag(request, comment_id, next=None):
    """
    Flags a comment. Confirmation on GET, action on POST.

    Templates: :template:`comments/flag.html`,
    Context:
        comment
            the flagged `comments.comment` object
    """
    comment = get_object_or_404(comments.get_model(),
                                pk=comment_id,
                                site__pk=settings.SITE_ID)

    # Flag on POST
    if request.method == 'POST':
        perform_flag(request, comment)
        return next_redirect(request,
                             fallback=next or 'comments-flag-done',
                             c=comment.pk)

    # Render a form on GET
    else:
        return render_to_response('comments/flag.html', {
            'comment': comment,
            "next": next
        }, template.RequestContext(request))
Esempio n. 6
0
def mod_delete(request, comment, next=None, template='comments/delete.html'):
    """
    Moderator cannot delete a comment, A comment is the propriety of the poster
    But moderator can hide a comment by moderating it...
    "can_moderate comments" permission required.
    Templates: :template:`comments/delete.html`,
    Context:
        comment
            the flagged `comments.comment` object
    """

    # Delete on POST
    if request.method == 'POST':
        # Flag the comment as deleted instead of actually deleting it.
        perform_moderation(request, comment)
        return next_redirect(request, fallback=next or 'comments-delete-done',
            c=comment.pk)


    # Render a confirmation form on GET
    else:
        print RequestContext(request)
        return render_to_response(template,
            {'comment': comment, 'post': comment.content_object, "next": next, "moderate":True},
                RequestContext(request)
        )
Esempio n. 7
0
def delete_comment(request, comment_id=None, next=None, moderate=False, template='comments/delete.html'):
    """
    Deletes a comment. Confirmation on GET, action on POST. User should have the
    "can_moderate comments" permission or own the comment
    """

    comment = get_object_or_404(django_comment.get_model(), pk=comment_id, site__pk=settings.SITE_ID)

    if request.user.has_perm("django.contrib.comments.can_moderate") and moderate:
        return mod_delete(request, comment, next, template)

    elif comment.user == request.user:
        # Delete on POST
        if request.method == 'POST':
            # Flag the comment as deleted instead of actually deleting it.
            perform_delete(request, comment)
            return next_redirect(request, fallback=next or 'comments-delete-done',
                c=comment.pk)

        # Render a confirmation form on GET
        else:
            return render_to_response(template,
                {'comment': comment, 'post': comment.content_object, "next": next},
                    RequestContext(request)
            )

    else:
        raise Http404
Esempio n. 8
0
def mark_as_spam(request, comment_id, next=None):
    comment = get_object_or_404(comments.get_model(), pk=comment_id, site__pk=settings.SITE_ID)

    if request.method == 'POST':
        perform_mark_as_spam(request, comment)
        return next_redirect(request, next, mark_as_spam_done, c=comment.pk)

    else:
        return render_to_response('comments/mark_spam.html',
            {'comment': comment, "next": next},
            template.RequestContext(request)
        )
def delete_comment(request, comment_id, next=None):
    """
    Deletes a comment. Confirmation on GET, action on POST.
    
    Templates: `comments/delete_by_user.html`, 
               `comments/delete_by_user_forbidden.html`
    Context:
        comment
            the deleted `comments.comment` object
    """
    comment = get_object_or_404(comment_app.get_model(), pk=comment_id, 
        site__pk=settings.SITE_ID)
    
    # Ensure requesting user is same user who posted comment
    if request.user != comment.user:
        t = loader.get_template('comments/delete_by_user_forbidden.html')
        c = RequestContext(request)
        return HttpResponseForbidden(t.render(c))
    
    # Check that user is not banned from commenting
    user_ip_address = request.META['REMOTE_ADDR']
    user_is_banned = \
        CommentsBannedFromIpAddress.objects.is_banned(user_ip_address)
    if user_is_banned:
        return HttpResponseForbidden()

    # Delete on POST
    if request.method == 'POST':
        comment.is_deleted_by_user = True
        comment.save()
        signals.comment_was_deleted_by_user.send(
            sender = comment.__class__,
            comment = comment,
            request = request
        )
        if request.is_ajax():
            return redirect('osl_comments.views.get_comment', 
                comment_id=comment_id)
        else:
            return next_redirect(request.POST.copy(), next, delete_by_user_done, 
            c=comment.pk)

    # Render a form on GET
    else:
        return render_to_response('comments/delete_by_user.html',
            {'comment': comment, "next": next},
            RequestContext(request)
        )
Esempio n. 10
0
File: views.py Progetto: 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, {}))
Esempio n. 11
0
def comment_delete(request, comment_id, next=None):
    """
    Override the django.contrib.comments.views.moderation.delete()
    No need to have the comments.can_moderate permission
    """
    comment = get_object_or_404(comments.get_model(), pk=comment_id, site__pk=settings.SITE_ID)

    # Delete on POST
    if request.method == 'POST':
        # Flag the comment as deleted instead of actually deleting it.
        perform_delete(request, comment)
        return next_redirect(request, next)

    # Render a form on GET
    else:
        return render_to_response(
            'comments/delete.html',
            {'comment': comment, "next": next},
            template.RequestContext(request)
        )
Esempio n. 12
0
def flag(request, comment_id, next=None):
    """
    Flags a comment. Confirmation on GET, action on POST.

    Templates: :template:`comments/flag.html`,
    Context:
        comment
            the flagged `comments.comment` object
    """
    comment = get_object_or_404(comments.get_model(), pk=comment_id, site__pk=settings.SITE_ID)

    # Flag on POST
    if request.method == 'POST':
        perform_flag(request, comment)
        return next_redirect(request.POST.copy(), next, flag_done, c=comment.pk)

    # Render a form on GET
    else:
        return render_to_response('comments/flag.html',
            {'comment': comment, "next": next},
            template.RequestContext(request)
        )
def comments_spam(request, comment_id, next=None):
    """
    Mark a comment as spam. Confirmation on GET, action on POST.

    Templates: `comments/spam.html`,
    Context:
        comment
            the spammed `comments.comment` object
    """
    comment = get_object_or_404(comments.get_model(),
                                pk=comment_id,
                                site__pk=settings.SITE_ID)

    # Flag on POST
    if request.method == 'POST':
        flag, created = comments.models.CommentFlag.objects.get_or_create(
            comment=comment, user=request.user, flag='spam')

        comment.is_removed = True
        comment.save()

        signals.comment_was_flagged.send(
            sender=comment.__class__,
            comment=comment,
            flag=flag,
            created=created,
            request=request,
        )
        return utils.next_redirect(request.POST.copy(),
                                   next,
                                   spam_done,
                                   c=comment.pk)

    # Render a form on GET
    else:
        return render_to_response('comments/spam.html', {
            'comment': comment,
            "next": next
        }, template.RequestContext(request))
def update_ip_address_ban(request, comment_id, next=None):
    
    comment = get_object_or_404(OslComment, pk=comment_id)
        
    if request.method == 'GET':
        banned = \
            CommentsBannedFromIpAddress.objects.is_banned(comment.ip_address)
        return render_to_response('comments/update_ip_address_ban.html',
            {'banned': banned},
            RequestContext(request)
        )
    
    if request.method == 'POST':
        data = request.POST
        banned_str = data.get('ban', None)
        if banned_str == 'True':
            banned = True
        elif banned_str == 'False':
            banned = False
        else:
            return HttpResponseBadRequest()
        
        try:
            ban = CommentsBannedFromIpAddress.objects.get(
                ip_address=comment.ip_address)
        except CommentsBannedFromIpAddress.DoesNotExist:
            ban = CommentsBannedFromIpAddress(ip_address=comment.ip_address)
        ban.comments_banned = banned
        ban.save()
        
        signals.ip_address_ban_was_updated.send(
            sender = comment.__class__,
            banned = banned,
            request = request
        )
        
        return next_redirect(request.POST.copy(), next, 
            update_ip_address_ban_done)
Esempio n. 15
0
def comments_spam(request, comment_id, next=None):
    """
    Mark a comment as spam. Confirmation on GET, action on POST.

    Templates: `comments/spam.html`,
    Context:
        comment
            the spammed `comments.comment` object
    """
    comment = get_object_or_404(comments.get_model(), pk=comment_id, site__pk=settings.SITE_ID)

    # Flag on POST
    if request.method == 'POST':
        flag, created = comments.models.CommentFlag.objects.get_or_create(
            comment = comment,
            user    = request.user,
            flag    = 'spam'
        )

        comment.is_removed = True
        comment.save()

        signals.comment_was_flagged.send(
            sender  = comment.__class__,
            comment = comment,
            flag    = flag,
            created = created,
            request = request,
        )
        return utils.next_redirect(request.POST.copy(), next, spam_done, c=comment.pk)

    # Render a form on GET
    else:
        return render_to_response('comments/spam.html',
            {'comment': comment, "next": next},
            template.RequestContext(request)
        )
def edit_comment(request, next=None):
    # get data
    data = request.POST.copy()
    next = data.get('next', next)
    
    # see if user wants to cancel
    cancel = 'cancel' in data
    if cancel:
        return redirect(data['cancel_url'])
    
    # get comment and raise error if id is wrong
    comment_id = data.get('comment_id')
    if comment_id is None:
        return CommentPostBadRequest("Missing comment id field.")
    try:
        comment = OslComment.objects.get(pk=comment_id)
    except ObjectDoesNotExist:
        return HttpResponseNotFound(
            "No comment matching with PK %r exists." % comment_id
        )
    except (ValueError, ValidationError) as e:
        return CommentPostBadRequest(
            "Attempting to get comment PK %r raised %s" % 
            (escape(comment_id), e.__class__.__name__)
        )
    
    # ensure user editing is same user who posted comment
    if comment.user != request.user:
        return HttpResponseForbidden("Cannot edit another user's comment.")
    
    # does the user want to preview the comment?
    preview = 'preview' in data
    
    # get a special comment form for editing
    form = OslEditCommentForm(data=data)
    
    # 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" % (comment.content_type.app_label, comment.content_type.model),
            "comments/%s_preview.html" % comment.content_type.app_label,
            # Now the usual directory based template heirarchy.
            "comments/%s/%s/preview.html" % (comment.content_type.app_label, comment.content_type.model),
            "comments/%s/preview.html" % comment.content_type.app_label,
            "comments/preview.html",
        ]
        return render_to_response(
            template_list, {
                "comment" : form.data.get("comment", ""),
                "form" : form,
                "next": next,
            },
            RequestContext(request, {})
        )
        
    responses = signals.comment_will_be_edited.send(
        sender  = comment.__class__,
        comment = comment,
        request = request
    )
    
    for (receiver, response) in responses:
        if response == False:
            return CommentPostBadRequest(
                "comment_will_be_edited receiver %r killed the comment" % receiver.__name__)
        
    # update comment content
    comment.comment = data.get('comment')
    comment.edit_timestamp = datetime.now()
    comment.save()
    
    signals.comment_was_edited.send(
        sender  = comment.__class__,
        comment = comment,
        request = request
    )
    
    if request.is_ajax():
        return redirect('osl_comments.views.get_comment', comment_id=comment.pk)
    else:
        return next_redirect(data, next, comment_edited)
Esempio n. 17
0
File: utils.py Progetto: hawkerpl/k2
 def confirmed(request, next, comment, **msg_kwargs):
     message_func(request, message % msg_kwargs, fail_silently=True)
     if comment.get_absolute_url():
         return HttpResponseRedirect(comment.get_absolute_url(anchor_pattern="#comment-%(id)s"))
     return next_redirect(request.POST.copy(), next, None, comment=comment.pk)
Esempio n. 18
0
def post_comment(request, next=None, using=None, object_pk=None, ctype=None, curcomment=None, templates=None):
    """Post a comment.

    """

    # Fill out some initial data fields from an authenticated user, if present
    data = request.POST.copy()
    # Look up the object we're trying to comment about
    ctype = data.get("content_type")
    object_pk = data.get("object_pk")
    # if user is not already authenticated, redirect to login
    if not request.user.is_authenticated():
        # and after login, redirect here again
        return redirect('/login/?next=%s' % data.get("next"))

    if not data.get('name', ''):
        data["name"] = request.user.get_full_name() or request.user.get_username()

    if  (ctype is None or object_pk is None) and curcomment is None:
        return CommentPostBadRequest("Missing content_type, object_pk or comment_id field.")

    # we got the ctype and object_pk but not comment_id
    if curcomment is None:
        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__))

    else :
        target =  curcomment.content_object

    # Construct the comment form
    form = django_comment.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 the form is valide,  create the comment
    if form.is_valid():
        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
        )
        return next_redirect(request, fallback=next or 'comments-comment-done',
            c=comment._get_pk_val())

    else :
        ctx = {
            "comment": curcomment,
            "form": form,
            "post": target,
            "object_pk": object_pk,
            "ctype": ctype,
            "next": data.get("next", next),
        }

        return render_to_response(
                templates,
                ctx,
                RequestContext(request, {})
            )
Esempio n. 19
0
	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())

comment_done = confirmation_view(
	template = "comments/posted.html",
	doc = """Display a "comment was posted" success page."""
)
Esempio n. 20
0
    responses = signals.review_will_be_posted.send(
        sender  = review.__class__,
        review = review,
        segments = segments,
        request = request
    )

    for (receiver, response) in responses:
        if response == False:
            return ReviewPostBadRequest(
                "review_will_be_posted receiver %r killed the review" % receiver.__name__)

    # Save the review and signal that it was saved
    review.save()
    for segment in segments:
        segment.review = review
        segment.save()

    signals.review_was_posted.send(
        sender  = review.__class__,
        review = review,
        request = request
    )

    return next_redirect(data, next, 'reviews-review-done', c=review._get_pk_val())

review_done = confirmation_view(
    template = "reviews/posted.html",
    doc = """Display a "review was posted" success page."""
)
Esempio n. 21
0
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

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

    # 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())
def edit(request, comment_id, next=None):
    """
    Edit a comment.
    
    Requires HTTP POST and "can change comments" or "can moderate comments",
    permission. Users can also only edit comments they own, unless they are
    granted "comments.can_moderate" permissions.
    
    If ``POST['submit'] == "preview"`` or there are errors,
    a preview template ``comments/preview.html`` will be rendered.
    
    Templates: `comments/edit.html`,
    Context:
        comment
            the `comments.comment` object to be edited.
    """
    comment = get_object_or_404(comments.get_model(), pk=comment_id, site__pk=settings.SITE_ID)
    
    # Make sure user has correct permissions to change the comment,
    # or return a 401 Unauthorized error.
    if not (request.user == comment.user and request.user.has_perm("comments.change_comment")
            or request.user.has_perm("comments.can_moderate")):
        return HttpResponse("Unauthorized", status=401)
    
    # Populate POST data with all required initial data
    # unless they are already in POST
    data = request.POST.copy()
    if not data.get("user_name", ""):
        data["user_name"] = request.user.get_full_name() or request.user.username
    if not data.get("user_email"):
        data["user_email"] = request.user.email
    
    next = data.get("next", next)
    CommentEditForm = comments_extension.get_edit_form()
    form = CommentEditForm(data, instance=comment)
    
    if form.security_errors():
        # NOTE: security hash fails!
        return CommentEditBadRequest(
            "The comment form failed security verification: %s" % \
                escape(str(form.security_errors())))
    
    # If there are errors, or if a preview is requested
    if form.errors or "preview" in data:
        app_label, model = (form.instance.content_type.app_label, form.instance.content_type.model)
        template_search_list = [
            "comments/%s/%s/edit-preview.html" % (app_label, model),
            "comments/%s/edit-preview.html" % model,
            "comments/edit-preview.html"
        ]
        return render_to_response(
            template_search_list, {
                "comment_obj": comment,
                "comment": form.data.get("comment", ""),
                "form": form,
                "next": next,
            },
            RequestContext(request, {})
        )
        
    # Otherwise, try to save the comment and emit signals
    if form.is_valid():
        MODERATOR_EDITED = "moderator edited"
        flag, created = comments.models.CommentFlag.objects.get_or_create(
            comment = form.instance,
            user = request.user,
            flag = MODERATOR_EDITED
        )
        
        form.instance.is_removed = False
        form.save()
        
        signals.comment_was_flagged.send(
            sender = comment.__class__,
            comment = comment,
            flag = flag,
            created = created,
            request = request
        )
        
        return next_redirect(request, next, edit_done, c=comment.pk)
    
    else:
        # If we got here, raise Bad Request error.
        return CommentEditBadRequest("Could not complete request!")
Esempio n. 23
0
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

    # 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 = apps.get_model(ctype)
        target = model._default_manager.using(using).get(pk=object_pk)
    except TypeError:
        return CommentPostBadRequest("Invalid content_type value: %r" %
                                     escape(ctype))
    except LookupError:
        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 == 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(request,
                         fallback=next or 'comments-comment-done',
                         c=comment._get_pk_val())
Esempio n. 24
0
def post_comment(request, next=None):
    """
    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 = MpttComment.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 = MpttCommentForm(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", ""),
                "form" : form,
                "allow_post": not form.errors
            },
            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__)

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

    if is_ajax:
        data['next'] = None

    return next_redirect(data, next, 'comments_comment_done%s' % (is_ajax and '_ajax' or ''), c=comment._get_pk_val())
Esempio n. 25
0
def post_comment(request, next=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.
    """
    # get a sensible value for next
    next = next or request.POST.get('next') or request.GET.get('next')

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

    # If there are errors or if we requested a preview show the comment
    if form.errors or preview:
        template_list = [
            "comments/%s_%s_preview.html" % tuple(str(model._meta).split(".")),
            "comments/%s_preview.html" % model._meta.app_label,
            "comments/preview.html",
        ]
        return render_to_response(
            template_list, {
                "next": target.get_absolute_url(), # sent next to the template
                "comment" : form.data.get("comment", ""),
                "form" : form,
            },
            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__)

    # 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())
Esempio n. 26
0
    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(request, next, comment_done, c=comment._get_pk_val())

comment_done = confirmation_view(
    template = "comments/posted.html",
    doc = """Display a "comment was posted" success page."""
)

Esempio n. 27
0
    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())

comment_done = confirmation_view(
    template = "comments/posted.html",
    doc = """Display a "comment was posted" success page."""
)

Esempio n. 28
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 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

    response = _lookup_content_object(data)
    if isinstance(response, HttpResponse):
        return response
    else:
        target, parent_comment, model = response

    # 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
        ]
        data = {
            'comment': form.data.get("comment", ""),
            'parent': parent_comment,
            'level': parent_comment and parent_comment.level + 1 or 0,
            'title': form.data.get("title", ""),
            'submit_date': datetime.datetime.now(),
            'rght': 0,
            'lft': 0,
            'user': request.user,
            'user_name' : request.user.username,
        }
        comment = get_model()(**data)
        return TemplateResponse(request, template_list, {
            "comment" : comment,
            "preview" : True,
            "form" : form,
            "allow_post": not form.errors,
            "is_ajax" : is_ajax,
        })

    # Otherwise create the comment
    comment = form.get_comment_object()
    comment.ip_address = request.META.get("REMOTE_ADDR", None)
    comment.user = request.user
    comment.user_name = request.user.username

    # 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(request, next, 'comments-comment-done%s' % (is_ajax and '-ajax' or ''), c=comment._get_pk_val())
Esempio n. 29
0
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

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


    # 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
    if form.errors:
        messages.error(request, "Error al enviar su comentario, por favor complete todos los campos "
                                "del formulario.")
        return http.HttpResponseRedirect(request.POST.get('next'))


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

    _send_email(request)

    messages.success(request, "Gracias por su comentario, pronto responderemos su consulta.")
    return next_redirect(request, fallback=next or 'comments-comment-done',
        c=comment._get_pk_val())