Пример #1
0
def proxy_post_comment(request, next=None, using=None):
    # 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 ctype is None or object_pk is None:
        return CommentPostBadRequest("Missing content_type or object_pk field.")
    try:
        model = apps.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__))

    mail_has_commented.delay(request.user.username, data['comment'])

    if not request.user.is_admin:
        ActionService.comment(request.user, target)
    return post_comment(request, next, using)
Пример #2
0
def _lookup_content_object(data):
    # 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")

    if parent_pk:
        try:
            parent_comment = get_model().objects.get(pk=parent_pk)
            target = parent_comment.content_object
            model = target.__class__
        except get_model().DoesNotExist:
            return CommentPostBadRequest(
                "Parent comment with PK %r does not exist." % \
                    escape(parent_pk))
    elif ctype and object_pk:
        try:
            parent_comment = None
            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)))
    else:
        return CommentPostBadRequest("Missing content_type or object_pk field.")

    return (target, parent_comment, model)
    def _lookup_object(ctype=None, object_pk=None, using=None):
        if ctype is None or object_pk is None:
            return CommentPostBadRequest("Missing content_type or object_pk field.")
        try:
            model = apps.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__))

        return model, target
Пример #4
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_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 is_authenticated(request.user):
        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 = apps.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, LookupError):
        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 = get_comments_form()(target, data=data)

    # Check security information
    if form.security_errors():
        return CommentPostBadRequest(
            "The comment form failed security verification: {0}".format(
                form.security_errors()))

    # 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 is_authenticated(request.user):
        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)
Пример #5
0
def post_comment_ajax(request, using=None):
    """
    Post a comment, via an Ajax call. Most from django-fluent-comments
    """
    if not request.is_ajax():
        return HttpResponseBadRequest("Expecting Ajax call")

    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.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 = django_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 preview:
        comment = form.get_comment_object() if not form.errors else None
        if comment is not None and request.user.is_authenticated():
            comment.user = request.user
        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 = get_trusted_ip(request)
    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)

    return _ajax_result(request, form, "post", comment, object_id=object_pk)
    def post(self, request, next=None, using=None):
        # 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.get_username()
        data["email"] = request.user.email

        # Look up the object we're trying to comment about
        result = self._lookup_object(data.get("content_type"), data.get("object_pk"), using)
        if isinstance(result, CommentPostBadRequest):
            return result
        else:
            model, target = result

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

        # Construct the comment form
        form = django_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(request, template_list, {
                "comment": form.data.get("comment", ""),
                "form": form,
                "next": data.get("next", next),
            })

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

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

        # Add the tags that are extracted from the comment
        comment.tags.add(*tags)

        return next_redirect(request, fallback=next or 'comments-comment-done', c=comment._get_pk_val())
Пример #7
0
def post_comment(request, next=None, using=None, **kwargs):
    """
    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()

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

    # Construct the comment form
    form = get_form(request, 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 not form.is_valid():
        return render_to_response(
            'nkcomments/comment_form.html', {
                'object': target,
                "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

    premoderation = getattr(comment.content_object, 'premoderation', False)

    if premoderation:
        comment.is_public = False

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

    if comment.user:
        user_orgs = set(comment.user.organization_ids)
        idea_orgs = set(comment.content_object.target_organization_ids)
        for o_id in user_orgs & idea_orgs:
            CommentUserOrganisations(comment_id=comment.pk,
                                     organization_id=o_id).save()

    signals.comment_was_posted.send(sender=comment.__class__,
                                    comment=comment,
                                    request=request)

    model_name = 'idea' if model.__name__ == 'Idea' else 'question'

    if premoderation:
        messages.success(
            request,
            ugettext(
                "Kommenttisi on tallennettu. Kommentti tulee näkyviin, kun moderaattori on "
                "hyväksynyt sen."))

    return JsonResponse({
        'success':
        True,
        'next':
        reverse('content:comment_block_%s' % model_name,
                kwargs={'initiative_id': target.pk})
    })
Пример #8
0
def login_required_post_comment(request, *args, **kwargs):
    if not review_requested() or is_admin_or_root(request.user):
        return post_comment(request, *args, **kwargs)
    else:
        return CommentPostBadRequest("Comment not allowed.")
Пример #9
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,
                         'comments-comment-done%s' %
                         (is_ajax and '-ajax' or ''),
                         c=comment._get_pk_val())
Пример #10
0
def game_comment_post(request, next=None, using=None):
    """
    Post a comment.

    Modified version of the default post view for django_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.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 = django_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:
        return JsonResponse({
            'form_html': render_crispy_form(form),
            'success': False,
        })

    # 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
    )
    target.push_notification()
    return JsonResponse({
        'success': True,
    })