首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Django -如何拒绝用户在他自己的对象中投票?

Django -如何拒绝用户在他自己的对象中投票?
EN

Stack Overflow用户
提问于 2013-01-26 06:54:39
回答 1查看 205关注 0票数 1

我是Django的新手,对如何做到这一点有一些疑问。我已经安装了一个叫Django-voting的应用程序,https://github.com/jezdez/django-voting/

这个应用程序允许用户对自己的对象进行投票。我需要否认这一点,但不确定如何做到这一点。我如何才能知道对象的所有者?

我要重写的代码是这个视图:

代码语言:javascript
复制
def vote_on_object(request, model, direction, post_vote_redirect=None,
    object_id=None, slug=None, slug_field=None, template_name=None,
    template_loader=loader, extra_context=None, context_processors=None,
    template_object_name='object', allow_xmlhttprequest=False):
    """
    Generic object vote function.

    The given template will be used to confirm the vote if this view is
    fetched using GET; vote registration will only be performed if this
    view is POSTed.

    If ``allow_xmlhttprequest`` is ``True`` and an XMLHttpRequest is
    detected by examining the ``HTTP_X_REQUESTED_WITH`` header, the
    ``xmlhttp_vote_on_object`` view will be used to process the
    request - this makes it trivial to implement voting via
    XMLHttpRequest with a fallback for users who don't have JavaScript
    enabled.

    Templates:``<app_label>/<model_name>_confirm_vote.html``
    Context:
    object
        The object being voted on.
    direction
        The type of vote which will be registered for the object.
    """
    if allow_xmlhttprequest and request.is_ajax():
    return xmlhttprequest_vote_on_object(request, model, direction,
                                         object_id=object_id, slug=slug,
                                         slug_field=slug_field)

    if extra_context is None:
    extra_context = {}
    if not request.user.is_authenticated():
    return redirect_to_login(request.path)

    try:
    vote = dict(VOTE_DIRECTIONS)[direction]
    except KeyError:
    raise AttributeError("'%s' is not a valid vote type." % direction)

    # Look up the object to be voted on
    lookup_kwargs = {}
    if object_id:
    lookup_kwargs['%s__exact' % model._meta.pk.name] = object_id
    elif slug and slug_field:
    lookup_kwargs['%s__exact' % slug_field] = slug
    else:
    raise AttributeError('Generic vote view must be called with either '
                         'object_id or slug and slug_field.')
    try:
    obj = model._default_manager.get(**lookup_kwargs)
    except ObjectDoesNotExist:
    raise Http404('No %s found for %s.' %
                  (model._meta.app_label, lookup_kwargs))

    if request.method == 'POST':
    if post_vote_redirect is not None:
        next = post_vote_redirect
    elif 'next' in request.REQUEST:
        next = request.REQUEST['next']
    elif hasattr(obj, 'get_absolute_url'):
        if callable(getattr(obj, 'get_absolute_url')):
            next = obj.get_absolute_url()
        else:
            next = obj.get_absolute_url
    else:
        raise AttributeError('Generic vote view must be called with either '
                             'post_vote_redirect, a "next" parameter in '
                             'the request, or the object being voted on '
                             'must define a get_absolute_url method or '
                             'property.')
    Vote.objects.record_vote(obj, request.user, vote)
    return HttpResponseRedirect(next)
    else:
    if not template_name:
        template_name = '%s/%s_confirm_vote.html' % (
            model._meta.app_label, model._meta.object_name.lower())
    t = template_loader.get_template(template_name)
    c = RequestContext(request, {
        template_object_name: obj,
        'direction': direction,
    }, context_processors)
    for key, value in extra_context.items():
        if callable(value):
            c[key] = value()
        else:
            c[key] = value
    response = HttpResponse(t.render(c))
    return response

我想我必须在这里添加一些验证,

代码语言:javascript
复制
Vote.objects.record_vote(obj, request.user, vote)

关于这个话题有什么线索吗?

诚挚的问候,

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-01-26 08:06:54

这个应用程序不会管理一个user是否拥有任何他可以投票的object,所以你需要在代表一个能够投票的实体的每个模型中保持这种控制。例如,如果您有一个模型A,并且您希望知道哪个用户是A的所有者,那么您应该与模型A建立一个user关系来跟踪模型所有者用户。我们可以通过一个例子来表示:

代码语言:javascript
复制
from django.contrib.auth.models import User
from django.db import models
from django.contrib import messages

class A(models.Model):
    owner_user = models.ForeignKey(User)

因此,在代码的任何地方(在视图中或在验证方法中),您都可以这样做:

代码语言:javascript
复制
# I will call `user_who_votes`  the user who is making the action of voting
# if you are in a view or have a `request` instance, you can access to its instance,
# as surely you already know, with `user_who_votes = request.user`, always checking  
# this user is authenticated (`if request.user.is_authenticated():`).
try:
    # Checking if the user who is voting is `A`'s owner,
    # if he is, so you can register a message and show it
    # to the user when you estimate (it is only an idea,
    # maybe you can have a better option, of course). 
    a = A.objects.get(owner_user=user_who_votes)
    messages.add_message(request, messages.ERROR, 'You can not vote on your own entities.'))
except A.DoesNotexist:
    # In this point you are sure at all that `user_who_votes`
    # isn't the owner of `A`, so this user can vote.
    Vote.objects.record_vote(a, user_who_votes, vote)

希望这能对你有所帮助。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14531622

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档