Пример #1
0
def dislike(request, comment_id, next=None):
    """
    Dislike a comment. Confirmation on GET, action on POST.

    Templates: :template:`django_comments_xtd/dislike.html`,
    Context:
        comment
            the flagged `comments.comment` object
    """
    comment = get_object_or_404(get_comment_model(),
                                pk=comment_id,
                                site__pk=get_current_site_id(request))
    if not get_app_model_options(comment=comment)['allow_feedback']:
        ctype = ContentType.objects.get_for_model(comment.content_object)
        raise Http404("Comments posted to instances of '%s.%s' are not "
                      "explicitly allowed to receive 'disliked it' flags. "
                      "Check the COMMENTS_XTD_APP_MODEL_OPTIONS "
                      "setting." % (ctype.app_label, ctype.model))
    # Flag on POST
    if request.method == 'POST':
        perform_dislike(request, comment)
        return next_redirect(request,
                             fallback=(next or 'comments-xtd-dislike-done'),
                             c=comment.pk)
    # Render a form on GET
    else:
        flag_qs = comment.flags.prefetch_related('user')\
            .filter(flag=DISLIKEDIT_FLAG)
        users_dislikedit = [item.user for item in flag_qs]
        return render(
            request, 'django_comments_xtd/dislike.html', {
                'comment': comment,
                'already_disliked_it': request.user in users_dislikedit,
                'next': next
            })
Пример #2
0
    def render(self, context):
        if not isinstance(self.count, int):
            self.count = int(self.count.resolve(context))

        self.qs = XtdComment.objects.for_content_types(
            self.content_types,
            site=get_current_site_id(
                context.get('request'))).order_by('submit_date')[:self.count]

        strlist = []
        context_dict = context.flatten()
        for xtd_comment in self.qs:
            if self.template_path:
                template_arg = self.template_path
            else:
                template_arg = [
                    "django_comments_xtd/%s/%s/comment.html" %
                    (xtd_comment.content_type.app_label,
                     xtd_comment.content_type.model),
                    "django_comments_xtd/%s/comment.html" %
                    (xtd_comment.content_type.app_label, ),
                    "django_comments_xtd/comment.html"
                ]
            context_dict['comment'] = xtd_comment
            strlist.append(loader.render_to_string(template_arg, context_dict))
        return ''.join(strlist)
Пример #3
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(get_comment_model(),
                                pk=comment_id,
                                site__pk=get_current_site_id(request))
    if not get_app_model_options(comment=comment)['allow_flagging']:
        ctype = ContentType.objects.get_for_model(comment.content_object)
        raise Http404("Comments posted to instances of '%s.%s' are not "
                      "explicitly allowed to receive 'removal suggestion' "
                      "flags. Check the COMMENTS_XTD_APP_MODEL_OPTIONS "
                      "setting." % (ctype.app_label, ctype.model))
    # 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(request, 'comments/flag.html', {
            'comment': comment,
            'next': next
        })
Пример #4
0
    def render(self, context):
        context_dict = context.flatten()
        for attr in ['allow_flagging', 'allow_feedback', 'show_feedback']:
            context_dict[attr] = (getattr(self, attr, False)
                                  or context.get(attr, False))
        if self.obj:
            obj = self.obj.resolve(context)
            ctype = ContentType.objects.get_for_model(obj)
            flags_qs = CommentFlag.objects.filter(flag__in=[
                CommentFlag.SUGGEST_REMOVAL, LIKEDIT_FLAG, DISLIKEDIT_FLAG
            ]).prefetch_related('user')
            prefetch = Prefetch('flags', queryset=flags_qs)
            queryset = XtdComment\
                .objects\
                .prefetch_related(prefetch)\
                .filter(
                    content_type=ctype,
                    object_pk=obj.pk,
                    site__pk=get_current_site_id(context.get('request')),
                    is_public=True
                )
            comments = XtdComment.tree_from_queryset(
                queryset,
                with_flagging=self.allow_flagging,
                with_feedback=self.allow_feedback,
                user=context['user'])
            context_dict['comments'] = comments
        if self.cvars:
            for vname, vobj in self.cvars:
                context_dict[vname] = vobj.resolve(context)
        if not self.obj:
            # Then presume 'comments' exists in the context_dict or in context
            if "comments" in context_dict:
                comments = context_dict["comments"]
            elif "comments" in context:
                comments = context["comments"]
            else:
                raise TemplateSyntaxError(
                    "'render_xtdcomment_tree' doesn't "
                    "have 'comments' in the context and "
                    "neither have been provided with the "
                    "clause 'with'.")
            # empty list of comments
            if not comments:
                return ""

            ctype = comments[0]['comment'].content_type

        if self.template_path:
            template_arg = self.template_path
        else:
            template_arg = [
                "django_comments_xtd/%s/%s/comment_tree.html" %
                (ctype.app_label, ctype.model),
                "django_comments_xtd/%s/comment_tree.html" %
                (ctype.app_label, ), "django_comments_xtd/comment_tree.html"
            ]
        html = loader.render_to_string(template_arg, context_dict)
        return html
Пример #5
0
 def get_queryset(self):
     content_types = self.get_content_types()
     if content_types is None:
         return None
     return XtdComment.objects.for_content_types(
         content_types,
         site=get_current_site_id(self.request)
     )\
         .filter(is_removed=False)\
         .order_by('submit_date')
Пример #6
0
 def render(self, context):
     if not isinstance(self.count, int):
         self.count = int(self.count.resolve(context))
     self.qs = XtdComment.objects.for_content_types(
             self.content_types,
             site=get_current_site_id(context.get('request'))
         )\
         .order_by('submit_date')[:self.count]
     context[self.as_varname] = self.qs
     return ''
Пример #7
0
 def render(self, context):
     obj = self.obj.resolve(context)
     ctype = ContentType.objects.get_for_model(obj)
     queryset = XtdComment.objects.filter(content_type=ctype,
                                          object_pk=obj.pk,
                                          site__pk=get_current_site_id(
                                              context.get('request')),
                                          is_public=True)
     dic_list = XtdComment.tree_from_queryset(
         queryset, with_feedback=self.with_feedback, user=context['user'])
     context[self.var_name] = dic_list
     return ''
Пример #8
0
 def get_queryset(self):
     content_type_arg = self.kwargs.get('content_type', None)
     object_pk_arg = self.kwargs.get('object_pk', None)
     app_label, model = content_type_arg.split("-")
     try:
         content_type = ContentType.objects.get_by_natural_key(
             app_label, model)
     except ContentType.DoesNotExist:
         qs = XtdComment.objects.none()
     else:
         qs = XtdComment.objects.filter(content_type=content_type,
                                        object_pk=object_pk_arg,
                                        site__pk=get_current_site_id(
                                            self.request),
                                        is_public=True)
     return qs
Пример #9
0
 def render(self, context):
     context_dict = context.flatten()
     for attr in ['allow_flagging', 'allow_feedback', 'show_feedback']:
         context_dict[attr] = (getattr(self, attr, False)
                               or context.get(attr, False))
     if self.obj:
         obj = self.obj.resolve(context)
         ctype = ContentType.objects.get_for_model(obj)
         queryset = XtdComment.objects.filter(content_type=ctype,
                                              object_pk=obj.pk,
                                              site__pk=get_current_site_id(
                                                  context.get('request')),
                                              is_public=True)
         comments = XtdComment.tree_from_queryset(
             queryset,
             with_flagging=self.allow_flagging,
             with_feedback=self.allow_feedback,
             user=context['user'])
         context_dict['comments'] = comments
     if self.cvars:
         for vname, vobj in self.cvars:
             context_dict[vname] = vobj.resolve(context)
     if not self.obj:
         # Then presume 'comments' exists in the context.
         try:
             ctype = context['comments'][0]['comment'].content_type
         except Exception:
             raise TemplateSyntaxError(
                 "'render_xtdcomment_tree' doesn't "
                 "have 'comments' in the context and "
                 "neither have been provided with the "
                 "clause 'with'.")
     if self.template_path:
         template_arg = self.template_path
     else:
         template_arg = [
             "django_comments_xtd/%s/%s/comment_tree.html" %
             (ctype.app_label, ctype.model),
             "django_comments_xtd/%s/comment_tree.html" %
             (ctype.app_label, ), "django_comments_xtd/comment_tree.html"
         ]
     html = loader.render_to_string(template_arg, context_dict)
     return html
Пример #10
0
 def render(self, context):
     obj = self.obj.resolve(context)
     ctype = ContentType.objects.get_for_model(obj)
     flags_qs = CommentFlag.objects.filter(flag__in=[
         CommentFlag.SUGGEST_REMOVAL, LIKEDIT_FLAG, DISLIKEDIT_FLAG
     ]).prefetch_related('user')
     prefetch = Prefetch('flags', queryset=flags_qs)
     queryset = XtdComment\
         .objects\
         .prefetch_related(prefetch)\
         .filter(
             content_type=ctype,
             object_pk=obj.pk,
             site__pk=get_current_site_id(context.get('request')),
             is_public=True
         )
     dic_list = XtdComment.tree_from_queryset(
         queryset, with_feedback=self.with_feedback, user=context['user'])
     context[self.var_name] = dic_list
     return ''
Пример #11
0
 def get_queryset(self, **kwargs):
     content_type_arg = self.kwargs.get('content_type', None)
     object_pk_arg = self.kwargs.get('object_pk', None)
     app_label, model = content_type_arg.split("-")
     try:
         content_type = ContentType.objects.get_by_natural_key(
             app_label, model)
     except ContentType.DoesNotExist:
         qs = XtdComment.objects.none()
     else:
         flags_qs = CommentFlag.objects.filter(flag__in=[
             CommentFlag.SUGGEST_REMOVAL, LIKEDIT_FLAG, DISLIKEDIT_FLAG
         ]).prefetch_related('user')
         prefetch = Prefetch('flags', queryset=flags_qs)
         qs = XtdComment\
             .objects\
             .prefetch_related(prefetch)\
             .filter(
                 content_type=content_type,
                 object_pk=object_pk_arg,
                 site__pk=get_current_site_id(self.request),
                 is_public=True
             )
     return qs
def commentbox_props(obj, user, request=None):
    """
    Returns a JSON object with the initial props for the CommentBox component.

    The returned JSON object contains the following attributes::
        {
            comment_count: <int>,  // Count of comments posted to the object.
            allow_comments: <bool>,  // Whether to allow comments to this post.
            current_user: <str as "user_id:user_name">,
            is_authenticated: <bool>,  // Whether current_user is authenticated.
            request_name: <bool>,  // True when auth user has no actual name.
            request_email_address: <bool>,  // True when auth user has no email.
            allow_flagging: false,
            allow_feedback: false,
            show_feedback: false,
            can_moderate: <bool>,  // Whether current_user can moderate.
            poll_interval: 2000, // Check for new comments every 2 seconds.
            feedback_url: <api-url-to-send-like/dislike-feedback>,
            delete_url: <api-url-for-moderators-to-remove-comment>,
            login_url: settings.LOGIN_URL,
            reply_url: <api-url-to-reply-comments>,
            flag_url: <api-url-to-suggest-comment-removal>,
            list_url: <api-url-to-list-comments>,
            count_url: <api-url-to-count-comments>,
            send_url: <api-irl-to-send-a-comment>,
            form: {
                content_type: <value>,
                object_pk: <value>,
                timestamp: <value>,
                security_hash: <value>
            },
            login_url: <only_when_user_is_not_authenticated>,
            like_url: <only_when_user_is_not_authenticated>,
            dislike_url: <only_when_user_is_not_authenticated>
        }
    """
    def _reverse(*args, **kwargs):
        """do not inject request to avoid http:// urls on https:// only sites"""
        return reverse(*args, **kwargs)

    form = CommentSecurityForm(obj)
    ctype = ContentType.objects.get_for_model(obj)
    queryset = XtdComment.objects.filter(content_type=ctype,
                                         object_pk=obj.pk,
                                         site__pk=get_current_site_id(request),
                                         is_public=True)
    ctype_slug = "%s-%s" % (ctype.app_label, ctype.model)
    d = {
        "comment_count":
        queryset.count(),
        "allow_comments":
        True,
        "current_user":
        "******",
        "request_name":
        False,
        "request_email_address":
        False,
        "is_authenticated":
        False,
        "allow_flagging":
        False,
        "allow_feedback":
        False,
        "show_feedback":
        False,
        "can_moderate":
        False,
        "poll_interval":
        2000,
        "feedback_url":
        _reverse("comments-xtd-api-feedback"),
        "delete_url":
        _reverse("comments-delete", args=(0, )),
        "delete_url_own":
        _reverse("comments-xtd-delete-own-comment", args=(0, )),
        "reply_url":
        _reverse("comments-xtd-reply", kwargs={'cid': 0}),
        "edit_url":
        _reverse("comments-xtd-reply", kwargs={'cid': 0}),
        "flag_url":
        _reverse("comments-flag", args=(0, )),
        "list_url":
        _reverse('comments-xtd-api-list',
                 kwargs={
                     'content_type': ctype_slug,
                     'object_pk': obj.id
                 }),
        "count_url":
        _reverse('comments-xtd-api-count',
                 kwargs={
                     'content_type': ctype_slug,
                     'object_pk': obj.id
                 }),
        "send_url":
        _reverse("comments-xtd-api-create"),
        "form": {
            "content_type": form['content_type'].value(),
            "object_pk": form['object_pk'].value(),
            "timestamp": form['timestamp'].value(),
            "security_hash": form['security_hash'].value()
        }
    }
    try:
        user_is_authenticated = user.is_authenticated()
    except TypeError:  # Django >= 1.11
        user_is_authenticated = user.is_authenticated
    if user and user_is_authenticated:
        d['current_user'] = "******" % (
            user.pk, settings.COMMENTS_XTD_API_USER_REPR(user))
        d['is_authenticated'] = True
        d['can_moderate'] = user.has_perm("django_comments.can_moderate")
        d['request_name'] = True if not len(user.get_full_name()) else False
        d['request_email_address'] = True if not user.email else False
    else:
        d['login_url'] = "/admin/login/"
        d['like_url'] = reverse("comments-xtd-like", args=(0, ))
        d['dislike_url'] = reverse("comments-xtd-dislike", args=(0, ))

    return d
Пример #13
0
 def render(self, context):
     context[self.as_varname] = self.qs.filter(
         site=get_current_site_id(context.get('request'))).count()
     return ''