0

我想检查是否允许用户注册特定事件。我想为了节省代码,我可以像login_required装饰器一样在 和 之间进行url()操作MyClass.as_view()。但是我怎么得到那个蛞蝓呢?还是这个解决方案完全错误?(不幸的是,我不能使用,user_passes_test因为我不想在用户上测试一些东西,而是在 url 上。)

所以我尝试了这个:

视图.py

from registration.models import Event
from django.utils import timezone
from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse

def reg_is_open(event_slug):
    """
    Return True if registration is open.
    """
    event = get_object_or_404(Event, slug=event_slug)
    if event.open_date <= timezone.now() and event.cut_off >= timezone.now():
        return True

def allow_view(cls, **initkwargs):
    """
    Check weather registration is open and user is logged in.
    Returns to registration start page if registration is closed.
    """
    slug = initkwargs.get('event') # Does not work!
    if not reg_is_open(slug):
        return HttpResponseRedirect(reverse('registration:event_index', args=slug))
    return login_required(cls.as_view(**initkwargs))
    # Also works when I remove **initkwargs. That means that what I'm looking for just passes...

网址.py

from django.conf.urls import patterns, url, include
from registration import views

event_patterns = patterns('', 
    url(r'^person/$', views.allow_view(views.PersonList), name='person_list'), 
    # instead of 
    # url(r'^person/$', login_required(views.PersonList.as_view()), name='person_list'),
    # ...

urlpatterns = patterns('',
    url(r'^(?P<event>[-a-zA-Z0-9_]+)/$', views.EventDetails.as_view(), name='event_index'),
    url(r'^(?P<event>[-a-zA-Z0-9_]+)/', include(event_patterns)),
    # ...
4

1 回答 1

0

如果我理解正确,您的观点是DetailView事件,对吗?在这种情况下,请使用以下内容:

class EventDetailView(DetailView):
    model = Event

    def dispatch(self, request, *args, **kwargs):
        if self.request.user not in self.object.registered_users.all():
            return HttpResponseForbidden()
        else:
            return super(EventDetailView, self).dispatch(request, *args, **kwargs)

这假设您在UserEvent模型之间有一个 M2M 密钥,registered_usersEvent侧面调用;更改代码以适合您的情况。

于 2013-08-31T10:56:38.320 回答