2016-03-23 9 views
1

私は2つのグループ(教授、学生)を作りたいと思います。また、生徒のコースの作成と削除を制限したいと考えています。Djangoグループとアクセス許可

views.py:

def is_professor(function=None): 

    def _is_professor(u): 
     if user.groups.filter(name='Professor').exists(): 
      return True 
     else: 
      raise HttpResponseForbidden 
    return _is_professor(function) 

class ListCourseView(ListView): 

    model = Course 
    template_name = 'course_list.html' 
    fields = '__all__' 

@is_professor 
class CreateCourseView(CreateView): 

    def get_queryset(self, request): 
     if not request.user.is_superuser: 
      return False 

    model = Course 
    template_name = 'course/edit_course.html' 
    fields = '__all__' 

    def get_success_url(self): 
     return reverse('courses-list') 

    def get_context_data(self, **kwargs): 

     context = super(CreateCourseView, self).get_context_data(**kwargs) 
     context['action'] = reverse('courses-new') 

     return context 

class UpdateCourseView(UpdateView): 

    model = Course 
    template_name = 'course/edit_course.html' 
    fields = '__all__' 

    def get_success_url(self): 
     return reverse('courses-list') 

def get_context_data(self, **kwargs): 

    context = super(UpdateCourseView, self).get_context_data(**kwargs) 
    context['action'] = reverse('courses-edit', 
           kwargs={'pk': self.get_object().id}) 

    return context 

class DeleteCourseView(DeleteView): 

    model = Course 
    template_name = 'course/delete_course.html' 

    def get_success_url(self): 
     return reverse('courses-list') 

models.py

class Course(models.Model): 
    name = models.CharField(
    max_length=255, 
    ) 

    def __str__(self): 
     return ' '.join([ 
     self.name 
     ]) 



class UserProfile(models.Model): 
    user = models.OneToOneField(User) 

    picture = models.ImageField(upload_to='profile_images', blank=True) 

    class Meta: 
     permissions = (('add_course', 'Add course'),) 

    def __unicode__(self): 
     return self.user.username 

これは私が試したものです。まず、私はエラー

NameError: global name 'user' is not defined.

を取得し、第二に、私はまだこれがうまくいくとは思わない:)

答えて

0

私は、ユーザーがここに

def is_professor(function=None): 

    def _is_professor(u): 
     if user.groups.filter(name='Professor').exists(): 
      return True 
     else: 
      raise HttpResponseForbidden 
    return _is_professor(function) 

定義されていないので、最初のエラーがあると思うすべての関数_is_professor(u)でrequest.userにする必要があります

+0

AttributeError:タイプオブジェクト 'CreateCourseView'に属性 'groups'がありません /adminページにグループを追加しようとしましたが、動作していません。 – ssapp

+0

これは私の悪いことでした。私は答えを更新しました – rishabsaraf93

+0

もし私が次のように書くならば: def _is_professor(リクエスト): \t \t user = request.user \tuser.groups.filter(name = 'Professor')の場合はです。()が存在する: \t \t \tリターン他の真 \t \t:HttpResponseForbidden \tリターン_is_professor(機能) はAttributeError \t \t \t昇給:型オブジェクトは、 'CreateCourseView' 属性」ユーザーの何を持っていません。 私は問題がmodels.pyにあると思います。 – ssapp

2

私のジャンゴプロジェクトで何かしたことは:

は私が権限を確認する関数を定義し、ユーザーが認証されている場合:

from django.contrib.auth.decorators import user_passes_test 

def group_required(*group_names): 
    """Requires user membership in at least one of the groups passed in.""" 
    def in_groups(u): 
     if u.is_authenticated(): 
      if bool(u.groups.filter(name__in=group_names)) | u.is_superuser: 
       return True 
     return False 

    return user_passes_test(in_groups, login_url='403') 

をし、私は私の機能のためのデコレータとしてこの関数に渡さ:あなたはマルチ宣言することができ、この方法では

from whatever import group_required 

@group_required('Professor') 
def action_only_for_professor(request): 
    # do things 

@group_required('Student') 
def action_only_for_student(request): 
    # do other things 

このような機能のグループ:

@group_required('Professor', 'Student', 'Administrator', ...) 

このトリックは、作成するメソッドでのみ機能します。 クラスで同じことをしたい場合は、django-braces(e.q. http://django-braces.readthedocs.org/en/latest/index.html)をチェックすることをお勧めします。

from braces.views import GroupRequiredMixin 

class CreateCourseView(CreateView, GroupRequiredMixin): 
    group_required = u"Professor" 

    def get_queryset(self, request): 
     if not request.user.is_superuser: 
      return False 

    model = Course 
    template_name = 'course/edit_course.html' 
    fields = '__all__' 

    def get_success_url(self): 
     return reverse('courses-list') 

    def get_context_data(self, **kwargs): 

     context = super(CreateCourseView, self).get_context_data(**kwargs) 
     context['action'] = reverse('courses-new') 

     return context 

、あなたのクラスで複数のグループのアクセス許可を使用したい場合は、ちょうどこのようにそれを実行します:

group_required = [u"Professor", u"Student", u"Administrator", etc...] 

ジャンゴ - 括弧はパーミッションをチェックするのは非常に強力です Djangoの中括弧は、このように動作します(LoginRequiredMixinで)、匿名で(AnonymousrequiredMixin)、スーパーユーザー(SuperuserRequiredMixin)、取得済み(PermissionRequiredMixin)、または複数のアクセス許可(MultiplePermissionRequiredMixin)、さらに多くのものがあるかどうかをチェックできるという点で、 !あなたはちょうどあなたが使用したい適切なミックスインを使用してクラスを継承しなければならない。

はそれに役立つことを願って、と)すべてのこと:)についてのあなたの帰りを待っているi 'は、ユーザーの私は「U」に変更

+0

ああ、私は忘れて、group_requiredデコレータ、またはdjango braces mixinを使用して、あなたのdjangoプロジェクトにdifferentsグループを作成する必要があります。 –

+0

私はまだ2番目の方法(中括弧)を使用してすべてのユーザーとコースを作成することができます... なぜ 'u'は、group_nameのinfrontですか? – ssapp

+0

私は確信していませんが、django-bracesに関するそのような情報はありませんが、Pythonの場合は、文字列をunicodeとみなし、group_nameのinfrontの関心を考慮する必要があります。 –

関連する問題