def rating(request):
    """
    Handle a ``RatingForm`` submission and redirect back to its
    related object.
    """
    response = initial_validation(request, "rating")
    if isinstance(response, HttpResponse):
        return response
    obj, post_data = response
    url = add_cache_bypass(obj.get_absolute_url().split("#")[0])
    response = redirect(url + "#rating-%s" % obj.id)
    rating_form = RatingForm(request, obj, post_data)
    if rating_form.is_valid():
        rating_form.save()
        if request.is_ajax():
            # Reload the object and return the rating fields as json.
            obj = obj.__class__.objects.get(id=obj.id)
            rating_name = obj.get_ratingfield_name()
            json = {}
            for f in ("average", "count", "sum"):
                json["rating_" + f] = getattr(obj, "%s_%s" % (rating_name, f))
            response = HttpResponse(dumps(json))
        if rating_form.undoing:
            ratings = set(rating_form.previous) ^ set([rating_form.current])
        else:
            ratings = rating_form.previous + [rating_form.current]
        set_cookie(response, "mezzanine-rating", ",".join(ratings))
    return response
def comment(request, template="generic/comments.html", extra_context=None):
    """
    Handle a ``ThreadedCommentForm`` submission and redirect back to its
    related object.
    """
    response = initial_validation(request, "comment")
    if isinstance(response, HttpResponse):
        return response
    obj, post_data = response
    form_class = import_dotted_path(settings.COMMENT_FORM_CLASS)
    form = form_class(request, obj, post_data)
    if form.is_valid():
        url = obj.get_absolute_url()
        if is_spam(request, form, url):
            return redirect(url)
        comment = form.save(request)
        response = redirect(add_cache_bypass(comment.get_absolute_url()))
        # Store commenter's details in a cookie for 90 days.
        for field in ThreadedCommentForm.cookie_fields:
            cookie_name = ThreadedCommentForm.cookie_prefix + field
            cookie_value = post_data.get(field, "")
            set_cookie(response, cookie_name, cookie_value)
        return response
    elif request.is_ajax() and form.errors:
        return HttpResponse(dumps({"errors": form.errors}))
    # Show errors with stand-alone comment form.
    context = {"obj": obj, "posted_comment_form": form}
    context.update(extra_context or {})
    return TemplateResponse(request, template, context)
Beispiel #3
0
def rating(request):
    """
    Handle a ``RatingForm`` submission and redirect back to its
    related object.
    """
    try:
        model = get_model(*request.POST["content_type"].split(".", 1))
        obj = model.objects.get(id=request.POST["object_pk"])
        url = add_cache_bypass(obj.get_absolute_url()) + "#rating-%s" % obj.id
    except (KeyError, TypeError, AttributeError, ObjectDoesNotExist):
        # Something was missing from the post so abort.
        return HttpResponseRedirect("/")
    try:
        rating_value = int(request.POST["value"])
    except (KeyError, ValueError):
        return HttpResponseRedirect(url)
    # There can only be one ``RatingField``, find its manager.
    for field in obj._meta.many_to_many:
        if isinstance(field, RatingField):
            rating_manager = getattr(obj, field.name)
            break
    else:
        raise TypeError("%s doesn't contain a RatingField." % obj)
    ratings = request.COOKIES.get("mezzanine-rating", "").split(",")
    rating_string = "%s.%s" % (request.POST["content_type"],
                               request.POST["object_pk"])
    if rating_string in ratings:
        # Already rated so abort.
        return HttpResponseRedirect(url)
    rating_manager.add(Rating(value=rating_value))
    response = HttpResponseRedirect(url)
    ratings.append(rating_string)
    expiry = 60 * 60 * 24 * 365
    set_cookie(response, "mezzanine-rating", ",".join(ratings), expiry)
    return response
Beispiel #4
0
def rating(request):
    """
    Handle a ``RatingForm`` submission and redirect back to its
    related object.
    """
    response = initial_validation(request, "rating")
    if isinstance(response, HttpResponse):
        return response
    obj, post_data = response
    url = add_cache_bypass(obj.get_absolute_url().split("#")[0])
    response = redirect(url + "#rating-%s" % obj.id)
    rating_form = RatingForm(request, obj, post_data)
    if rating_form.is_valid():
        rating_form.save()
        if request.is_ajax():
            # Reload the object and return the rating fields as json.
            obj = obj.__class__.objects.get(id=obj.id)
            rating_name = obj.get_ratingfield_name()
            json = {}
            for f in ("average", "count", "sum"):
                json["rating_" + f] = getattr(obj, "%s_%s" % (rating_name, f))
            response = HttpResponse(dumps(json))
        ratings = ",".join(rating_form.previous + [rating_form.current])
        set_cookie(response, "mezzanine-rating", ratings)
    return response
def comment(request, template="generic/comments.html"):
    """
    Handle a ``ThreadedCommentForm`` submission and redirect back to its
    related object.
    """
    response = initial_validation(request, "comment")
    if isinstance(response, HttpResponse):
        return response
    obj, post_data = response
    resource_mode = post_data.get('resource-mode', 'view')
    request.session['resource-mode'] = resource_mode
    form = ThreadedCommentForm(request, obj, post_data)
    if form.is_valid():
        url = obj.get_absolute_url()
        if is_spam(request, form, url):
            return redirect(url)
        comment = form.save(request)
        response = redirect(add_cache_bypass(comment.get_absolute_url()))
        # Store commenter's details in a cookie for 90 days.
        # for field in ThreadedCommentForm.cookie_fields:
        #     cookie_name = ThreadedCommentForm.cookie_prefix + field
        #     cookie_value = post_data.get(field, "")
        #     set_cookie(response, cookie_name, cookie_value)
        return response
    elif request.is_ajax() and form.errors:
        return HttpResponse(dumps({"errors": form.errors}))
    # Show errors with stand-alone comment form.
    context = {"obj": obj, "posted_comment_form": form}
    response = render(request, template, context)
    return response
    def save(self, request):
        """
        Saves a new comment and sends any notification emails.
        """
        comment = self.get_comment_object()
        obj = comment.content_object
        if request.user.is_authenticated():
            comment.user = request.user
            comment.user_name = best_name(comment.user)

        comment.by_author = request.user == getattr(obj, "user", None)
        comment.ip_address = ip_for_request(request)
        comment.replied_to_id = self.data.get("replied_to")
        comment.save()
        comment_was_posted.send(sender=comment.__class__, comment=comment,
                                request=request)
        notify_emails = split_addresses(settings.COMMENTS_NOTIFICATION_EMAILS)
        notify_emails.append(obj.user.email)
        reply_to_comment = comment.replied_to
        if reply_to_comment is not None:
            notify_emails.append(reply_to_comment.user.email)
        if notify_emails:
            subject = "[HydroShare Support] New comment by {c_name} for: {res_obj}".format(
                c_name=comment.user_name, res_obj=str(obj))
            context = {
                "comment": comment,
                "comment_url": add_cache_bypass(comment.get_absolute_url()),
                "request": request,
                "obj": obj,
            }
            send_mail_template(subject, "email/comment_notification",
                               settings.DEFAULT_FROM_EMAIL, notify_emails,
                               context)

        return comment
Beispiel #7
0
 def save(self, request):
     """
     Saves a new comment and sends any notification emails.
     """
     comment = self.get_comment_object()
     obj = comment.content_object
     if request.user.is_authenticated():
         comment.user = request.user
     comment.by_author = request.user == getattr(obj, "user", None)
     comment.ip_address = ip_for_request(request)
     comment.replied_to_id = self.data.get("replied_to")
     comment.save()
     comment_was_posted.send(sender=comment.__class__,
                             comment=comment,
                             request=request)
     notify_emails = split_addresses(settings.COMMENTS_NOTIFICATION_EMAILS)
     if notify_emails:
         subject = _("New comment for: ") + str(obj)
         context = {
             "comment": comment,
             "comment_url": add_cache_bypass(comment.get_absolute_url()),
             "request": request,
             "obj": obj,
         }
         send_mail_template(subject, "email/comment_notification",
                            settings.DEFAULT_FROM_EMAIL, notify_emails,
                            context)
     return comment
Beispiel #8
0
def rating(request):
    """
    Handle a ``RatingForm`` submission and redirect back to its
    related object.
    """
    try:
        model = get_model(*request.POST["content_type"].split(".", 1))
        obj = model.objects.get(id=request.POST["object_pk"])
        url = add_cache_bypass(obj.get_absolute_url()) + "#rating-%s" % obj.id
    except (KeyError, TypeError, AttributeError, ObjectDoesNotExist):
        # Something was missing from the post so abort.
        return HttpResponseRedirect("/")
    try:
        rating_value = int(request.POST["value"])
    except (KeyError, ValueError):
        return HttpResponseRedirect(url)
    # There can only be one ``RatingField``, find its manager.
    for field in obj._meta.many_to_many:
        if isinstance(field, RatingField):
            rating_manager = getattr(obj, field.name)
            break
    else:
        raise TypeError("%s doesn't contain a RatingField." % obj)
    ratings = request.COOKIES.get("mezzanine-rating", "").split(",")
    rating_string = "%s.%s" % (request.POST["content_type"],
                               request.POST["object_pk"])
    if rating_string in ratings:
        # Already rated so abort.
        return HttpResponseRedirect(url)
    rating_manager.add(Rating(value=rating_value))
    response = HttpResponseRedirect(url)
    ratings.append(rating_string)
    expiry = 60 * 60 * 24 * 365
    set_cookie(response, "mezzanine-rating", ",".join(ratings), expiry)
    return response
Beispiel #9
0
def comment(request, template="generic/comments.html"):
    """
    Handle a ``ThreadedCommentForm`` submission and redirect back to its
    related object.
    """
    response = initial_validation(request, "comment")
    if isinstance(response, HttpResponse):
        return response
    obj, post_data = response
    form = ThreadedCommentForm(request, obj, post_data)
    if form.is_valid():
        url = obj.get_absolute_url()
        if is_spam(request, form, url):
            return redirect(url)
        comment = form.save(request)
        response = redirect(add_cache_bypass(comment.get_absolute_url()))
        # Store commenter's details in a cookie for 90 days.
        for field in ThreadedCommentForm.cookie_fields:
            cookie_name = ThreadedCommentForm.cookie_prefix + field
            cookie_value = post_data.get(field, "")
            set_cookie(response, cookie_name, cookie_value)
        return response
    elif request.is_ajax() and form.errors:
        return HttpResponse(dumps({"errors": form.errors}))
    # Show errors with stand-alone comment form.
    context = {"obj": obj, "posted_comment_form": form}
    response = render(request, template, context)
    return response
Beispiel #10
0
 def save(self, request):
     """
     Saves a new comment and sends any notification emails.
     """
     comment = self.get_comment_object()
     obj = comment.content_object
     if request.user.is_authenticated():
         comment.user = request.user
     comment.by_author = request.user == getattr(obj, "user", None)
     comment.ip_address = ip_for_request(request)
     comment.replied_to_id = self.data.get("replied_to")
     comment.save()
     comment_was_posted.send(sender=comment.__class__, comment=comment,
                             request=request)
     notify_emails = split_addresses(settings.COMMENTS_NOTIFICATION_EMAILS)
     if notify_emails:
         subject = _("New comment for: ") + str(obj)
         context = {
             "comment": comment,
             "comment_url": add_cache_bypass(comment.get_absolute_url()),
             "request": request,
             "obj": obj,
         }
         send_mail_template(subject, "email/comment_notification",
                            settings.DEFAULT_FROM_EMAIL, notify_emails,
                            context)
     return comment
Beispiel #11
0
def comment(request, template="generic/comments.html"):
    """
    Handle a ``ReviewForm`` submission and redirect back to its
    related object.
    """
    response = initial_validation(request, "comment")
    if isinstance(response, HttpResponse):
        return response
    obj, post_data = response
    form = ReviewForm(request, obj, request.POST )
    if form.is_valid():
        url = obj.get_absolute_url()
        if is_spam(request, form, url):
            return redirect(url)
        comment = form.save(request)
        response = redirect(add_cache_bypass(comment.get_absolute_url()))
        # Store commenter's details in a cookie for 90 days.
        for field in ReviewForm.cookie_fields:
            cookie_name = ReviewForm.cookie_prefix + field
            cookie_value = post_data.get(field, "")
            set_cookie(response, cookie_name, cookie_value)
        """
            Send activity feed to those who follow this vendor page.
        """
        if request.user.is_authenticated():
            action.send(obj, verb=settings.GOT_REVIEW_VERB, target=comment )
        return response
    elif request.is_ajax() and form.errors:
        return HttpResponse(dumps({"errors": form.errors}))
    # Show errors with stand-alone comment form.
    context = {"obj": obj, "posted_comment_form": form}
    response = render(request, template, context)
    return response
Beispiel #12
0
def set_device(request, device=""):
    """
    Sets a device name in a cookie when a user explicitly wants to go
    to the site for a particular device (eg mobile).
    """
    response = redirect(add_cache_bypass(next_url(request) or "/"))
    set_cookie(response, "mezzanine-device", device, 60 * 60 * 24 * 365)
    return response
Beispiel #13
0
def set_device(request, device=""):
    """
    Sets a device name in a cookie when a user explicitly wants to go
    to the site for a particular device (eg mobile).
    """
    response = redirect(add_cache_bypass(request.GET.get("next", "/")))
    set_cookie(response, "mezzanine-device", device, 60 * 60 * 24 * 365)
    return response
Beispiel #14
0
def comment(request, template="generic/comments.html"):
    """
    Handle a ``ThreadedCommentForm`` submission and redirect back to its
    related object.
    """

    post_data = request.POST
    settings.use_editable()
    if settings.COMMENTS_ACCOUNT_REQUIRED:
        if not request.user.is_authenticated():
            # Account required but user isn't authenticated - store
            # their post data in the session and redirect to login.
            request.session["unauthenticated_comment"] = post_data
            error(request, _("You must log in to comment. Please log in or "
                             "sign up, and your comment will be posted."))
            url = "%s?next=%s" % (settings.LOGIN_URL, reverse("comment"))
            return redirect(url)
        elif "unauthenticated_comment" in request.session:
            # User has logged in after post data being stored in the
            # session for an unauthenticated comment post, so use it.
            post_data = request.session.pop("unauthenticated_comment")

    try:
        model = get_model(*post_data["content_type"].split(".", 1))
        obj = model.objects.get(id=post_data["object_pk"])
    except (KeyError, TypeError, AttributeError, ObjectDoesNotExist):
        # Something was missing from the post so abort.
        return HttpResponseRedirect("/")

    form = ThreadedCommentForm(request, obj, post_data)
    if form.is_valid():
        url = obj.get_absolute_url()
        if is_spam(request, form, url):
            return redirect(url)
        comment = form.get_comment_object()
        if request.user.is_authenticated():
            comment.user = request.user
        comment.by_author = request.user == getattr(obj, "user", None)
        comment.ip_address = request.META.get("HTTP_X_FORWARDED_FOR",
                                              request.META["REMOTE_ADDR"]).split(',')[0].strip()
        comment.replied_to_id = post_data.get("replied_to")
        comment.save()
        comment_was_posted.send(sender=comment.__class__, comment=comment,
                                request=request)
        url = add_cache_bypass(comment.get_absolute_url())
        response = HttpResponseRedirect(url)
        # Store commenter's details in a cookie for 90 days.
        cookie_expires = 60 * 60 * 24 * 90
        for field in ThreadedCommentForm.cookie_fields:
            cookie_name = ThreadedCommentForm.cookie_prefix + field
            cookie_value = post_data.get(field, "")
            set_cookie(response, cookie_name, cookie_value, cookie_expires)
        return response
    else:
        # Show errors with stand-alone comment form.
        context = {"obj": obj, "posted_comment_form": form}
        return render(request, template, context)
Beispiel #15
0
def comment(request, template="generic/comments.html"):
    """
    Handle a ``ThreadedCommentForm`` submission and redirect back to its
    related object.
    """

    post_data = request.POST
    settings.use_editable()
    if settings.COMMENTS_ACCOUNT_REQUIRED:
        if not request.user.is_authenticated():
            # Account required but user isn't authenticated - store
            # their post data in the session and redirect to login.
            request.session["unauthenticated_comment"] = post_data
            error(request, _("You must log in to comment. Please log in or "
                             "sign up, and your comment will be posted."))
            url = "%s?next=%s" % (settings.LOGIN_URL, reverse("comment"))
            return redirect(url)
        elif "unauthenticated_comment" in request.session:
            # User has logged in after post data being stored in the
            # session for an unauthenticated comment post, so use it.
            post_data = request.session.pop("unauthenticated_comment")

    try:
        model = get_model(*post_data["content_type"].split(".", 1))
        obj = model.objects.get(id=post_data["object_pk"])
    except (KeyError, TypeError, AttributeError, ObjectDoesNotExist):
        # Something was missing from the post so abort.
        return HttpResponseRedirect("/")

    form = ThreadedCommentForm(request, obj, post_data)
    if form.is_valid():
        url = obj.get_absolute_url()
        if is_spam(request, form, url):
            return redirect(url)
        comment = form.get_comment_object()
        if request.user.is_authenticated():
            comment.user = request.user
        comment.by_author = request.user == getattr(obj, "user", None)
        comment.ip_address = request.META.get("HTTP_X_FORWARDED_FOR",
                                              request.META["REMOTE_ADDR"])
        comment.replied_to_id = post_data.get("replied_to")
        comment.save()
        comment_was_posted.send(sender=comment.__class__, comment=comment,
                                request=request)
        url = add_cache_bypass(comment.get_absolute_url())
        response = HttpResponseRedirect(url)
        # Store commenter's details in a cookie for 90 days.
        cookie_expires = 60 * 60 * 24 * 90
        for field in ThreadedCommentForm.cookie_fields:
            cookie_name = ThreadedCommentForm.cookie_prefix + field
            cookie_value = post_data.get(field, "")
            set_cookie(response, cookie_name, cookie_value, cookie_expires)
        return response
    else:
        # Show errors with stand-alone comment form.
        context = {"obj": obj, "posted_comment_form": form}
        return render(request, template, context)
Beispiel #16
0
    def save(self, request):
        """
        Saves a new comment and sends any notification emails.
        """
        comment = self.get_comment_object()
        obj = comment.content_object
        comment.user = request.user
        user_name = request.user.get_full_name()
        if not user_name:
            user_name = request.user.username

        comment.user_name = user_name
        # comment.email = request.user.email

        comment.by_author = request.user == getattr(obj, "user", None)
        comment.ip_address = ip_for_request(request)
        comment.replied_to_id = self.data.get("replied_to")

        # Mezzanine's duplicate check that also checks `replied_to_id`.
        lookup = {
            "content_type": comment.content_type,
            "object_pk": comment.object_pk,
            "user_name": comment.user_name,
            "user_email": comment.user_email,
            "user_url": comment.user_url,
            "replied_to_id": comment.replied_to_id,
        }
        for duplicate in self.get_comment_model().objects.filter(**lookup):
            if (duplicate.submit_date.date() == comment.submit_date.date() and
                    duplicate.comment == comment.comment):
                return duplicate

        comment.save()
        comment_was_posted.send(sender=comment.__class__, comment=comment,
                                request=request)
        notify_emails = split_addresses(settings.COMMENTS_NOTIFICATION_EMAILS)
        if notify_emails:
            subject = ugettext("New comment for: ") + str(obj)
            context = {
                "comment": comment,
                "comment_url": add_cache_bypass(comment.get_absolute_url()),
                "request": request,
                "obj": obj,
            }
            send_mail_template(subject, "email/comment_notification",
                               settings.DEFAULT_FROM_EMAIL, notify_emails,
                               context)
        return comment
Beispiel #17
0
    def save(self, request):
        """
        Saves a new comment and sends any notification emails.
        """
        comment = self.get_comment_object()
        obj = comment.content_object
        if is_authenticated(request.user):
            comment.user = request.user
        comment.by_author = request.user == getattr(obj, "user", None)
        comment.ip_address = ip_for_request(request)
        comment.replied_to_id = self.data.get("replied_to")

        # Mezzanine's duplicate check that also checks `replied_to_id`.
        lookup = {
            "content_type": comment.content_type,
            "object_pk": comment.object_pk,
            "user_name": comment.user_name,
            "user_email": comment.user_email,
            "user_url": comment.user_url,
            "replied_to_id": comment.replied_to_id,
        }
        for duplicate in self.get_comment_model().objects.filter(**lookup):
            if (duplicate.submit_date.date() == comment.submit_date.date()
                    and duplicate.comment == comment.comment):
                return duplicate

        comment.save()
        comment_was_posted.send(sender=comment.__class__,
                                comment=comment,
                                request=request)
        notify_emails = split_addresses(settings.COMMENTS_NOTIFICATION_EMAILS)
        if notify_emails:
            subject = ugettext("New comment for: ") + str(obj)
            context = {
                "comment": comment,
                "comment_url": add_cache_bypass(comment.get_absolute_url()),
                "request": request,
                "obj": obj,
            }
            send_mail_template(
                subject,
                "email/comment_notification",
                settings.DEFAULT_FROM_EMAIL,
                notify_emails,
                context,
            )
        return comment
Beispiel #18
0
def spam(request, template="generic/comments.html"):
    response = initial_validation(request, "spam")
    if isinstance(response, HttpResponse):
        return response
    obj, post_data = response
    form = CommentFlagForm(request, obj, post_data)
    if form.is_valid():
        url = obj.get_absolute_url()
        if is_spam(request, form, url):
            return redirect(url)
        form.save(request)
        messages.info(request, _('Se guardó como spam'))
        response = redirect(add_cache_bypass(obj.get_absolute_url()))
        # for field in CommentFlagForm.cookie_fields:
        #     cookie_name = CommentFlagForm.cookie_prefix + field
        #     cookie_value = post_data.get(field, "")
        #     set_cookie(response, cookie_name, cookie_value)
        return response
    context = {"obj": obj, "spam_form": form}
    response = render(request, template, context)
    return response
Beispiel #19
0
def spam(request, template="generic/comments.html"):
    response = initial_validation(request, "spam")
    if isinstance(response, HttpResponse):
        return response
    obj, post_data = response
    form = CommentFlagForm(request, obj, post_data)
    if form.is_valid():
        url = obj.get_absolute_url()
        if is_spam(request, form, url):
            return redirect(url)
        form.save(request)
        messages.info(request, _('Se guardó como spam'))
        response = redirect(add_cache_bypass(obj.get_absolute_url()))
        # for field in CommentFlagForm.cookie_fields:
        #     cookie_name = CommentFlagForm.cookie_prefix + field
        #     cookie_value = post_data.get(field, "")
        #     set_cookie(response, cookie_name, cookie_value)
        return response
    context = {"obj": obj, "spam_form": form}
    response = render(request, template, context)
    return response
Beispiel #20
0
def comment_on_review(request, template="generic/comments.html"):
    """
    Handle a ``ThreadedCommentForm`` submission and redirect back to its
    related object.
    """

    response = initial_validation(request, "comment_on_review")
    if isinstance(response, HttpResponse):
        return response
    obj, post_data = response

    form = ThreadedCommentForm(request, obj, request.POST)
    if form.is_valid():
        url = obj.get_absolute_url()
        if is_spam(request, form, url):
            return redirect(url)  
        comment = form.save(request)
        if request.is_ajax():
            #comment = form.save(request)
            comments = [comment]

            html = render_to_string('generic/includes/subcomment.html', { 'comments_for_thread': comments }) 
            res = {'html': html}
            return HttpResponse( simplejson.dumps(res), 'application/json' )
        else:
            response = redirect(add_cache_bypass(comment.get_absolute_url()))
            return response

    elif request.is_ajax() and form.errors:
        return HttpResponse(dumps({"errors": form.errors}))

    # Show errors with stand-alone comment form.
    if not request.is_ajax():
        context = {"obj": obj, "posted_comment_form": form}
        response = render(request, template, context)
        return response
def rating(request):
    """
    Handle a ``RatingForm`` submission and redirect back to its
    related object.
    """
    response = initial_validation(request, "rating")
    if isinstance(response, HttpResponse):
        return response
    obj, post_data = response
    url = obj.get_absolute_url()
    url = add_cache_bypass(url.split("#")[0]) + "#rating-%s" % obj.id
    response = redirect(url)
    rating_form = RatingForm(request, obj, post_data)
    if rating_form.is_valid():
        rating_form.save()
        if request.is_ajax():
            # Reload the object and return the new rating.
            obj = obj.__class__.objects.get(id=obj.id)
            fields = ("rating_avg", "rating_count", "rating_sum")
            json = dumps(dict([(f, getattr(obj, f)) for f in fields]))
            response = HttpResponse(json)
        ratings = ",".join(rating_form.previous + [rating_form.current])
        set_cookie(response, "mezzanine-rating", ratings)
    return response
Beispiel #22
0
def comment(request, template="generic/comments.html"):
    """
    Handle a ``ThreadedCommentForm`` submission and redirect back to its
    related object.
    """

    post_data = request.POST
    settings.use_editable()
    if settings.COMMENTS_ACCOUNT_REQUIRED:
        if not request.user.is_authenticated():
            # Account required but user isn't authenticated - store
            # their post data in the session and redirect to login.
            request.session["unauthenticated_comment"] = post_data
            error(request, _("You must log in to comment. Please log in or "
                             "sign up, and your comment will be posted."))
            url = "%s?next=%s" % (settings.LOGIN_URL, reverse("comment"))
            return redirect(url)
        elif "unauthenticated_comment" in request.session:
            # User has logged in after post data being stored in the
            # session for an unauthenticated comment post, so use it.
            post_data = request.session.pop("unauthenticated_comment")

    try:
        model = get_model(*post_data["content_type"].split(".", 1))
        obj = model.objects.get(id=post_data["object_pk"])
    except (KeyError, TypeError, AttributeError, ObjectDoesNotExist):
        # Something was missing from the post so abort.
        return HttpResponseRedirect("/")

    form = ThreadedCommentForm(request, obj, post_data)
    if form.is_valid():
        url = obj.get_absolute_url()
        if is_spam(request, form, url):
            return redirect(url)
        comment = form.get_comment_object()
        if request.user.is_authenticated():
            comment.user = request.user
        comment.by_author = request.user == getattr(obj, "user", None)
        comment.ip_address = request.META.get("HTTP_X_FORWARDED_FOR",
                                              request.META["REMOTE_ADDR"])
        comment.replied_to_id = post_data.get("replied_to")
        comment.save()
        comment_was_posted.send(sender=comment.__class__, comment=comment,
                                request=request)
        # Send notification emails.
        comment_url = add_cache_bypass(comment.get_absolute_url())
        #=======================================================================
        # send email to reply or post people,instead of ADMINS
        #=======================================================================
        try:
            from mezzanine.blog.models import BlogPost
            notify_emails = [BlogPost.objects.get(id=comment.object_pk).user.email]
            
            if comment.threadedcomment.replied_to != None:
                other_email = comment.threadedcomment.replied_to.user_email             
                notify_emails += [other_email]
#            print notify_emails
        except:            
            notify_emails = filter(None, [addr.strip() for addr in
                            settings.COMMENTS_NOTIFICATION_EMAILS.split(",")])
        if notify_emails:
            subject = _("New comment for: ") + unicode(obj)
            context = {
                "comment": comment,
                "comment_url": comment_url,
                "request": request,
                "obj": obj,
            }
            send_mail_template(subject, "email/comment_notification",
                               settings.DEFAULT_FROM_EMAIL, notify_emails,
                               context, fail_silently=settings.DEBUG)

        response = HttpResponseRedirect(comment_url)
        # Store commenter's details in a cookie for 90 days.
        cookie_expires = 60 * 60 * 24 * 90
        for field in ThreadedCommentForm.cookie_fields:
            cookie_name = ThreadedCommentForm.cookie_prefix + field
            cookie_value = post_data.get(field, "")
            set_cookie(response, cookie_name, cookie_value, cookie_expires)
        return response
    else:
        # Show errors with stand-alone comment form.
        context = {"obj": obj, "posted_comment_form": form}
        return render(request, template, context)
Beispiel #23
0
    def save(self, request):
        """
        Saves a new comment and sends any notification emails.
        """
        post_data = request.POST
        review = self.get_comment_object()
        obj = review.content_object
        if request.user.is_authenticated():
            review.user = request.user
            review.user_name = review.user.username
        review.by_author = request.user == getattr(obj, "user", None)
        review.ip_address = ip_for_request(request)
        review.replied_to_id = self.data.get("replied_to")

        requiredreviewrating_name = obj.get_requiredreviewratingfield_name()
        requiredreviewrating_manager = getattr(obj, requiredreviewrating_name)
        optionalreviewrating_name = obj.get_optionalreviewratingfield_name()
        optionalreviewrating_manager = getattr(obj, optionalreviewrating_name)
        
        if request.user.is_authenticated():
            requiredreviewrating_instance = RequiredReviewRating(user=request.user)
        else:
            requiredreviewrating_instance = RequiredReviewRating()

        if request.user.is_authenticated():
            optionalreviewrating_instance = OptionalReviewRating(user=request.user)
        else:
            optionalreviewrating_instance = OptionalReviewRating()

        if (post_data.get("title")):
            review.title = post_data.get("title")
        if (post_data.get("overall_value")):
            review.overall_value = post_data.get("overall_value")
            requiredreviewrating_instance.overall_value = review.overall_value
        if (post_data.get("price_value")):
            review.price_value = post_data.get("price_value")
            requiredreviewrating_instance.price_value = review.price_value
        if (post_data.get("website_ex_value")):
            review.website_ex_value = post_data.get("website_ex_value")
            requiredreviewrating_instance.website_ex_value = review.website_ex_value
        if (post_data.get("quality_value")):
            review.quality_value = post_data.get("quality_value")
            requiredreviewrating_instance.quality_value = review.quality_value
        if (post_data.get("service_value")):
            review.service_value = post_data.get("service_value")
            requiredreviewrating_instance.service_value = review.service_value
        if (post_data.get("shop_again")):
            review.shop_again = post_data.get("shop_again")
            requiredreviewrating_instance.shop_again = review.shop_again
        if (post_data.get("exchange_value")):
            review.exchange_value = post_data.get("exchange_value")
            optionalreviewrating_instance.exchange_value = review.exchange_value
        review.save()
        
        if isinstance(obj, BlogPost):
            blog_category = post_data.get("category")
            bought_category  = None
            bought_category = BlogCategory.objects.get(slug=slugify(blog_category))
            review.bought_category.add(bought_category)

        # the primary key for review will be generated when it is saved
        # and the reviewrating will need to store that primary key
        requiredreviewrating_instance.commentid = review.pk        
        requiredreviewrating_manager.add(requiredreviewrating_instance)
            
        if post_data.get("exchange_value"):
            optionalreviewrating_instance.commentid = review.pk
            optionalreviewrating_manager.add(optionalreviewrating_instance)
        
        comment_was_posted.send(sender=review.__class__, comment=review,
                                request=request)
        notify_emails = split_addresses(settings.COMMENTS_NOTIFICATION_EMAILS)
        if notify_emails:
            subject = _("New comment for: ") + unicode(obj)
            context = {
                "comment": review,
                "comment_url": add_cache_bypass(comment.get_absolute_url()),
                "request": request,
                "obj": obj,
            }
            send_mail_template(subject, "email/comment_notification",
                               settings.DEFAULT_FROM_EMAIL, notify_emails,
                               context, fail_silently=settings.DEBUG)
        return review
Beispiel #24
0
def write_review(request, content_type_id, object_id, template="generic/includes/write_review.html"):
	store = request.GET.get('store', 'None')
	parent = None
	if store != 'None':
		store = store.lower()
		try:
			parent = BlogPost.objects.get(title__iexact=store)
			content_type_id = ContentType.objects.get_for_model(parent).pk
			object_id = parent.pk
		except:
			pass

	if not parent:
		ctype = get_object_or_404(ContentType, pk=content_type_id)
		parent = get_object_or_404(ctype.model_class(), pk=object_id)

	prefix = "write_review"

	if request.method == 'POST':
		response = initial_validation_review(request, prefix, content_type_id, object_id, store)

		if isinstance(response, HttpResponse):
		    return response
		obj, post_data = response

		form = ReviewForm(request, obj, request.POST)
		if form.is_valid() and request.user.is_authenticated():
			url = obj.get_absolute_url()
			if is_spam(request, form, url):
				return redirect(url)  
			comment = form.save(request)

			"""
				Send activity feed to those who follow this vendor page.
			"""
			if request.user.is_authenticated():
				action.send(obj, verb=settings.GOT_REVIEW_VERB, target=comment )

			if request.is_ajax():
				html = render_to_string('generic/includes/comment_ajax.html', { 'comment': comment, 'request':request }) 
				res = {'html': html,
					   'store': obj.title,
					   'success':True}
				response = HttpResponse( simplejson.dumps(res), 'application/json' )
				# Store commenter's details in a cookie for 90 days.
				for field in ReviewForm.cookie_fields:
					cookie_name = ReviewForm.cookie_prefix + field
					cookie_value = post_data.get(field, "")
					set_cookie(response, cookie_name, cookie_value)	
								
				return response
			else:
				response = redirect(add_cache_bypass(comment.get_absolute_url()))
				return response

		elif request.is_ajax() and form.errors:
			return HttpResponse( simplejson.dumps({"errors": form.errors,
										"success":False}), 'application/json')		
	else:
		post_data = None
		posted_session_key = "unauthenticated_" + prefix
		post_session_generic_review_store_key = "unauthenticated_store_" + prefix

		if posted_session_key in request.session:
			post_data = request.session.pop(posted_session_key)
			form = ReviewForm(request, parent, post_data)
			if post_session_generic_review_store_key in request.session:
				request.session.pop(post_session_generic_review_store_key)
		else:
			form = ReviewForm(request, parent)

		form.fields['overall_value'].widget 	= forms.HiddenInput()
		form.fields['price_value'].widget 		= forms.HiddenInput()
		form.fields['website_ex_value'].widget 	= forms.HiddenInput()
		form.fields['quality_value'].widget 	= forms.HiddenInput()
		form.fields['service_value'].widget 	= forms.HiddenInput()
		form.fields['exchange_value'].widget 	= forms.HiddenInput()

		action_url = reverse("write_review", kwargs={
														'content_type_id':content_type_id,
														'object_id':object_id
													})
		if store != 'None':
			action_url += '?store=' + store

		context = {"new_review":True,  "obj": parent, "posted_comment_form": form, "action_url": action_url }
		response = render(request, template, context)
		return response
Beispiel #25
0
def edit_review(request, review_id, template="generic/includes/write_review.html"):
	if not review_id :
		raise Http404()

	review_obj = Review.objects.get(id=review_id)

	if review_obj and review_obj.user != request.user:
		raise Http404()

	context = RequestContext(request)

	parent_obj = review_obj.content_object

	if request.method == 'POST':
		form = ReviewForm(request, parent_obj, request.POST )

		if form.is_valid():
			url = review_obj.get_absolute_url()
			if is_spam(request, form, url):
				return redirect(url)

			review_obj.comment             = form.cleaned_data['comment']
			review_obj.title               = form.cleaned_data['title']
			review_obj.overall_value       = form.cleaned_data['overall_value']
			review_obj.price_value         = form.cleaned_data['price_value']
			review_obj.website_ex_value    = form.cleaned_data['website_ex_value']
			review_obj.quality_value       = form.cleaned_data['quality_value']
			review_obj.service_value       = form.cleaned_data['service_value']
			exchange_value   			   = form.cleaned_data['exchange_value']
			"""
			exchange_value is not a required field. Can contain null data as well. Therefore need to handle it seperately.
			"""
			if exchange_value == '':
				review_obj.exchange_value = None
			else:
				review_obj.exchange_value = exchange_value

			review_obj.shop_again       = form.cleaned_data['shop_again']
			blog_category               = form.cleaned_data['category']
			bought_category             = None
			try:
				bought_category         = BlogCategory.objects.get(slug=slugify(blog_category))
			except:
				pass

			try:
				reviewRatingObj                    = RequiredReviewRating.objects.get(commentid=review_obj.id)
				reviewRatingObj.overall_value      = review_obj.overall_value
				reviewRatingObj.price_value        = review_obj.price_value
				reviewRatingObj.website_ex_value   = review_obj.website_ex_value
				reviewRatingObj.quality_value      = review_obj.quality_value
				reviewRatingObj.service_value      = review_obj.service_value
				reviewRatingObj.shop_again         = review_obj.shop_again
				reviewRatingObj.save()

				optReviewRatingObj                  = OptionalReviewRating.objects.get(commentid=review_obj.id)
				optReviewRatingObj.exchange_value   = review_obj.service_value
				optReviewRatingObj.save()
				
			except:
				pass

			review_obj.save()
			if bought_category:
				for blog_category in review_obj.bought_category.all():
					review_obj.bought_category.remove(blog_category)
				review_obj.bought_category.add(bought_category)

			if request.is_ajax():
				template = 'generic/includes/comment_ajax.html'
				review_page = request.GET.get('reviewpage', '0')

				if review_page == '1':
					template = 'generic/includes/review_ajax.html'

				html = render_to_string(template, { 'comment': review_obj, 'request':request }) 
				res = { 'html': html,
						'store' : review_obj.content_object.title,
				   		'success':True}
				response = HttpResponse( simplejson.dumps(res), 'application/json' )
			else:
				response = redirect(add_cache_bypass(review_obj.get_absolute_url()))

			return response

		elif form.errors:
			return HttpResponse(simplejson.dumps({"errors": form.errors}), 'application/json' )
	else:        
		data = {
			"comment"           : review_obj.comment,
			"title"             : review_obj.title,
			"overall_value"     : review_obj.overall_value,
			"price_value"       : review_obj.price_value,
			"website_ex_value"  : review_obj.website_ex_value,
			"quality_value"     : review_obj.quality_value,
			"service_value"     : review_obj.service_value,
			"exchange_value"    : review_obj.exchange_value,
			"shop_again"        : review_obj.shop_again,
			"category"          : review_obj.bought_category.all()[0] #we support multiple bought categoires but there's no multiselect option in UI.
		}

		form = ReviewForm(request, parent_obj, initial=data)
		form.fields['overall_value'].widget 	= forms.HiddenInput()
		form.fields['price_value'].widget 		= forms.HiddenInput()
		form.fields['website_ex_value'].widget 	= forms.HiddenInput()
		form.fields['quality_value'].widget 	= forms.HiddenInput()
		form.fields['service_value'].widget 	= forms.HiddenInput()
		form.fields['exchange_value'].widget 	= forms.HiddenInput()

		"""
			Review pages which list all the reviews require a template different than edit review template on store page.
			For such a case reviewpage=1 query parameter should be present.
		"""
		review_page = request.GET.get('reviewpage', '0')
		action_url = reverse("edit_review", kwargs={'review_id':review_id})
		action_url = action_url + '?reviewpage='+review_page

		context = {
				"posted_comment_form": form,
				"action_url":action_url,
				"new_review":False,
				"review_id": review_id
			}
		response =  render(request, template, context)

	return response