2017-10-29 3 views
1

, 나는 다음과 같이 사용자의 다른 유형을 가지고 :한 종류의 사용자가 django의 URL을 통해 다른 사용자의보기에 액세스하는 것을 거부하는 방법은 무엇입니까? 내 프로젝트에서

User |-Client |-Employee |-Technical Manager |-Service Manager |-Production Manager

없음 사용자가 url하여 다른 사용자의보기에 액세스 할 수 없습니다. 클라이언트는 기술 관리자의 프로필에 지정된 URL /officer/profile을 통해 기술 관리자의 프로필에 액세스 할 수 없습니다. 그런 다음 @permission_required(lambda u: u.has_perm('authentication.view_client'))

:이 같은 장식을 사용하여 각 뷰에 대해 다음

class Client(models.Model): class Meta: permissions = ( ('view_client', 'view_Client'), )

다음 models.pyClient class에서 이렇게하기 위해

, 나는이 코드를 사용 기술 관리자로 로그인하여이 URL로 액세스하려고합니다. /client/profile

그런 다음 오류 function object is not iterable이 있습니다.

authentication이라는 앱에서 내 사용자를 만들고있었습니다. models,py은 다음과 같습니다 를 '

@python_2_unicode_compatible 
class Profile(models.Model): 
    user = models.OneToOneField(User) 
    user_sex = (('MALE', 'Male'), ('FEMALE', 'Female')) 
    sex = models.CharField(max_length=6, default='Male', choices=user_sex) 
    address = models.CharField(max_length=250, null=True, blank=True) 
    city = models.CharField(max_length=250, null=True, blank=True) 
    state = models.CharField(max_length=250, null=True, blank=True) 
    country = models.CharField(max_length=250, null=True, blank=True) 
    phone = PhoneNumberField(blank=True) 
    zip = models.IntegerField(null=True, blank=True) 
    about = models.CharField(max_length=250, null=True, blank=True) 
    email_confirmed = models.BooleanField(default=False) 
    account_type = models.IntegerField(default=-1) 

    class Meta: 
     db_table = 'auth_profile' 


class Employee(models.Model): 
    user = models.OneToOneField(User) 
    manager = models.ForeignKey('self', null=True, on_delete=models.SET_NULL) 
    designation = models.CharField(max_length=6) 

    class Meta: 
     db_table = 'auth_employee' 


class Client(models.Model): 
    user = models.OneToOneField(User) 
    class Meta: 
     db_table = 'auth_client' 


@receiver(post_save, sender=User) 
def update_user_profile(sender, instance, created, **kwargs): 
    if created: 
     Profile.objects.create(user=instance) 
    instance.profile.save() 
    if instance.profile.account_type == 0: 
     if not Client.objects.filter(user=instance).exists(): 
      Client.objects.create(user=instance) 
      instance.client.save() 
     else: 
      instance.client.save() 
    if instance.profile.account_type == 1 or instance.profile.account_type == 2 or instance.profile.account_type == 3: 
     if not Employee.objects.filter(user=instance).exists(): 
      Employee.objects.create(user=instance) 
      instance.employee.save() 
     else: 
      instance.employee.save() 

'

프로필 클래스가 좀 큽니다. 그것을 무시하십시오. 이제 내가 원했던 것은 다른 사용자가 모든 유형을 만들 때마다 권한을 할당한다는 것입니다.

오류를 해결하는 방법과이를 수행하여 한 유형의 사용자가 URL을 입력하여 다른 사용자의보기에 액세스 할 수 없게하려면 어떻게해야합니까?

@login_required(login_url='/login/') 
@permission_required(lambda u: u.has_perm('authentication.view_client')) 
def contact(request): 
    user = request.user 
    if request.method == 'POST': 
     # form = ContactForm() 
     form = ContactForm(request.POST) 
     if form.is_valid(): 
      user.profile.address = form.cleaned_data.get('address') 
      user.profile.city = form.cleaned_data.get('city') 
      user.profile.state = form.cleaned_data.get('state') 
      user.profile.country = form.cleaned_data.get('country') 
      user.profile.phone = form.cleaned_data.get('phone') 
      user.profile.zip = form.cleaned_data.get('zip') 


      user.save() 
      messages.add_message(request, 
           messages.SUCCESS, 
           'Your contact was successfully edited.') 

    else: 

     form = ContactForm(instance=user, initial={ 
      'address': user.profile.address, 
      'city': user.profile.city, 
      'state': user.profile.state, 
      'country': user.profile.country, 
      'phone': user.profile.phone, 
      'zip': user.profile.zip, 
     }) 
    return render(request, 'client/client_contact.html', {'form': form}) 

그리고 내가 가진 오류 :

TypeError at /client/picture 

'function' object is not iterable 

Request Method:  GET 
Request URL: http://127.0.0.1:8000/client/picture 
Django Version:  1.11.6 
Exception Type:  TypeError 
Exception Value:  

'function' object is not iterable 

Exception Location:  /usr/local/lib/python2.7/dist-packages/django/contrib/auth/models.py in has_perms, line 285 
Python Executable: /usr/bin/python2.7 
Python Version:  2.7.12 
Python Path:  

['/home/shamsad/PycharmProjects/OpenGMS', 
'/home/shamsad/PycharmProjects/OpenGMS', 
'/usr/lib/python2.7', 
'/usr/lib/python2.7/plat-x86_64-linux-gnu', 
'/usr/lib/python2.7/lib-tk', 
'/usr/lib/python2.7/lib-old', 
'/usr/lib/python2.7/lib-dynload', 
'/home/shamsad/.local/lib/python2.7/site-packages', 
'/usr/local/lib/python2.7/dist-packages', 
'/usr/lib/python2.7/dist-packages', 
'/usr/lib/python2.7/dist-packages/PILcompat', 
'/usr/lib/python2.7/dist-packages/gtk-2.0'] 

Server time: Sun, 29 Oct 2017 16:21:25 +0000 
+0

당신이를 게시 할 수있는 예를 들어, 아마도 당신은 단지 Client 개체와 연관된 사용자에게 표시 할 뷰가 오류에 대한 전체 추적 및보기? 보기는 주어진 요청이 요청한 콘텐츠에 액세스 할 수 있는지 여부를 확인하는 곳입니다. – souldeux

+0

내 질문을 편집했습니다. – sphoenix

+0

또한 추적을 게시했습니다 – sphoenix

답변

0

편집 여기 souldeux

에서 주석 후 클라이언트가 자신의 연락처 정보를 업데이트 할 수 있습니다 내보기 중 하나입니다

permission_required 데코레이터에서 람다 함수를 전달하는 대신 권한 테스트를 역으로 다시 작성하십시오 ndalone 기능은 dispatch 방법에 작동하는 method_decorator를 통해 그것을 적용 : 당신은 또한 당신의 기능을 기반 뷰를 장식하는 @user_passes_test을 사용할 수 있습니다

https://docs.djangoproject.com/en/dev/topics/class-based-views/intro/#decorating-the-class

How to use permission_required decorators on django class-based views

.당신은 당신의 테스트에서 사용자 권한에 대한뿐만 아니라 확인할 수 있습니다

def user_has_client(user) 
    return hasattr(user, 'Client') 

@user_passes_test(user_has_client, login_url='/') 
def my_protected_view(request): 
    ... 

: https://docs.djangoproject.com/en/1.11/ref/contrib/auth/#django.contrib.auth.models.User.has_perm

+0

사용자가 생성 될 때마다 '게시물 신호'에 권한을 지정해야합니까? – sphoenix

+0

모든 사용자에 대해 일관된 동작을 원한다면 예. 다음은 그 작업을 수행하는 방법입니다 : https://stackoverflow.com/questions/20361235/django-set-user-permissions-when-user-is-automatically-created – souldeux

+0

'decorator, 독립 실행 형으로 권한 테스트 다시 작성 기능'나는이 부분을 이해하지 못했다. 미안하다. 지금까지 나는이 모델에서'meta' 클래스에서 권한을 사용해야한다는 것을 알고 있습니다. – sphoenix

관련 문제