How to edit user permission in Django Rest FrameworkDjango rest-framework per action permissionHow can i correctly pass arguments to classbasedviews testing Django Rest Framework?How to access current user in Django class based viewPermission checks in DRF viewsets are not working rightDjango POST request issue with modelDjango-Rest-Framework - How to serialize queryset from an unrelated model as nested serializerConnectionRefusedError in dJango rest api while registration processdjango-permission AuthorPermissionLogic not working in function based viewDjango DRF permissions on create related objectsDjango Rest Framework: serializer response error

Why does a perfectly-identical repetition of a drawing command given within an earlier loop 𝘯𝘰𝘵 produce exactly the same line?

Simple function that simulates survey results based on sample size and probability

I think I may have violated academic integrity last year - what should I do?

How do Human Traits Work?

Why does this if-statement combining assignment and an equality check return true?

Does the unit of measure matter when you are solving for the diameter of a circumference?

Does Nitrogen inside commercial airliner wheels prevent blowouts on touchdown?

Where have Brexit voters gone?

Can I install both XCode & Android Studio on MacBook Air with only 8 GB of Ram

Text at the right of icon

Is neural networks training done one-by-one?

How to know if a folder is a symbolic link?

Is it possible to play as a necromancer skeleton?

What was the idiom for something that we take without a doubt?

Should breaking down something like a door be adjudicated as an attempt to beat its AC and HP, or as an ability check against a set DC?

Where is the logic in castrating fighters?

Is there a way to make it so the cursor is included when I prtscr key?

Is the field of q-series 'dead'?

Did people go back to where they were?

If a person had control of every single cell of their body, would they be able to transform into another creature?

Is the Indo-European language family made up?

Is "cool" appropriate or offensive to use in IMs?

I unknowingly submitted plagarised work

Construct a word ladder



How to edit user permission in Django Rest Framework


Django rest-framework per action permissionHow can i correctly pass arguments to classbasedviews testing Django Rest Framework?How to access current user in Django class based viewPermission checks in DRF viewsets are not working rightDjango POST request issue with modelDjango-Rest-Framework - How to serialize queryset from an unrelated model as nested serializerConnectionRefusedError in dJango rest api while registration processdjango-permission AuthorPermissionLogic not working in function based viewDjango DRF permissions on create related objectsDjango Rest Framework: serializer response error






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








0















I am following the tutorial of django Rest Framework. I want to add user-based permission so that only authenticated user can view each user's detail information.
Objective : Anyone can view the UserList, but only owner can view its UserDetail.



models.py



class Meeting(models.Model):
created = models.DateTimeField(auto_now_add=True)
sinceWhen = models.DateTimeField(null=True)
tilWhen = models.DateTimeField(null=True)
owner = models.ForeignKey('auth.User', related_name='meetings', on_delete=models.CASCADE)
#highlighted = models.TextField()

def save(self, *args, **kwargs):
super(Meeting, self).save(*args, **kwargs)


class Meta:
ordering = ('created',)


views.py



from django.contrib.auth.models import User
# User is not created inside models.py

class UserList(generics.ListAPIView):
queryset = User.objects.all()
serializer_class = UserListSerializer

class UserDetail(generics.RetrieveAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly,)
# I added IsOwnerOrReadOnly to make it work, but this is the part where it causes error!


serializers.py



class UserSerializer(serializers.ModelSerializer):
meetings = serializers.PrimaryKeyRelatedField(many=True, queryset=Meeting.objects.all())
#owner = serializers.ReadOnlyField(source='owner.username')

class Meta:
model = User
fields = ('id', 'username', 'meetings',)

class UserListSerializer(serializers.ModelSerializer):
#meetings = serializers.PrimaryKeyRelatedField(many=True, queryset=Meeting.objects.all())

class Meta:
model = User
fields = ('username',)


permissions.py



from rest_framework import permissions

class IsOwnerOrReadOnly(permissions.BasePermission):
def has_object_permission(self, request, view, obj):

# Any permissions are only allowed to the owner of the meeting
return obj.owner == request.user


I overrode IsOwnerOrReadOnly so that only user can view the details of his/her user detail.
And add this to permission_class in views.py.



Then I got this error :



File "/home/tony/env/lib/python3.6/site-packages/rest_framework/views.py" in check_object_permissions
345. if not permission.has_object_permission(request, self, obj):

File "/home/tony/swpp_hw1/meetings/permissions.py" in has_object_permission
15. return obj.owner == request.user

Exception Type: AttributeError at /users/1/
Exception Value: 'User' object has no attribute 'owner'


I tried to add User class in models.py, but again it causes error...
How can solve this issue?










share|improve this question

















  • 1





    There is no owner on the User model. There is a reverse relationship named meetings to a Meeting model. > Anyone can view the UserList, but only owner can view its UserDetail. Your permission class just needs to test that obj == request.user. That means that the user that is being looked up is equal to the user that is performing the lookup. The meeting ownership will be handled inherently due to the data model i.e. The user detail view will only show meetings that the looked up user owns.

    – Joshua Taylor Eppinette
    Mar 24 at 6:10

















0















I am following the tutorial of django Rest Framework. I want to add user-based permission so that only authenticated user can view each user's detail information.
Objective : Anyone can view the UserList, but only owner can view its UserDetail.



models.py



class Meeting(models.Model):
created = models.DateTimeField(auto_now_add=True)
sinceWhen = models.DateTimeField(null=True)
tilWhen = models.DateTimeField(null=True)
owner = models.ForeignKey('auth.User', related_name='meetings', on_delete=models.CASCADE)
#highlighted = models.TextField()

def save(self, *args, **kwargs):
super(Meeting, self).save(*args, **kwargs)


class Meta:
ordering = ('created',)


views.py



from django.contrib.auth.models import User
# User is not created inside models.py

class UserList(generics.ListAPIView):
queryset = User.objects.all()
serializer_class = UserListSerializer

class UserDetail(generics.RetrieveAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly,)
# I added IsOwnerOrReadOnly to make it work, but this is the part where it causes error!


serializers.py



class UserSerializer(serializers.ModelSerializer):
meetings = serializers.PrimaryKeyRelatedField(many=True, queryset=Meeting.objects.all())
#owner = serializers.ReadOnlyField(source='owner.username')

class Meta:
model = User
fields = ('id', 'username', 'meetings',)

class UserListSerializer(serializers.ModelSerializer):
#meetings = serializers.PrimaryKeyRelatedField(many=True, queryset=Meeting.objects.all())

class Meta:
model = User
fields = ('username',)


permissions.py



from rest_framework import permissions

class IsOwnerOrReadOnly(permissions.BasePermission):
def has_object_permission(self, request, view, obj):

# Any permissions are only allowed to the owner of the meeting
return obj.owner == request.user


I overrode IsOwnerOrReadOnly so that only user can view the details of his/her user detail.
And add this to permission_class in views.py.



Then I got this error :



File "/home/tony/env/lib/python3.6/site-packages/rest_framework/views.py" in check_object_permissions
345. if not permission.has_object_permission(request, self, obj):

File "/home/tony/swpp_hw1/meetings/permissions.py" in has_object_permission
15. return obj.owner == request.user

Exception Type: AttributeError at /users/1/
Exception Value: 'User' object has no attribute 'owner'


I tried to add User class in models.py, but again it causes error...
How can solve this issue?










share|improve this question

















  • 1





    There is no owner on the User model. There is a reverse relationship named meetings to a Meeting model. > Anyone can view the UserList, but only owner can view its UserDetail. Your permission class just needs to test that obj == request.user. That means that the user that is being looked up is equal to the user that is performing the lookup. The meeting ownership will be handled inherently due to the data model i.e. The user detail view will only show meetings that the looked up user owns.

    – Joshua Taylor Eppinette
    Mar 24 at 6:10













0












0








0








I am following the tutorial of django Rest Framework. I want to add user-based permission so that only authenticated user can view each user's detail information.
Objective : Anyone can view the UserList, but only owner can view its UserDetail.



models.py



class Meeting(models.Model):
created = models.DateTimeField(auto_now_add=True)
sinceWhen = models.DateTimeField(null=True)
tilWhen = models.DateTimeField(null=True)
owner = models.ForeignKey('auth.User', related_name='meetings', on_delete=models.CASCADE)
#highlighted = models.TextField()

def save(self, *args, **kwargs):
super(Meeting, self).save(*args, **kwargs)


class Meta:
ordering = ('created',)


views.py



from django.contrib.auth.models import User
# User is not created inside models.py

class UserList(generics.ListAPIView):
queryset = User.objects.all()
serializer_class = UserListSerializer

class UserDetail(generics.RetrieveAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly,)
# I added IsOwnerOrReadOnly to make it work, but this is the part where it causes error!


serializers.py



class UserSerializer(serializers.ModelSerializer):
meetings = serializers.PrimaryKeyRelatedField(many=True, queryset=Meeting.objects.all())
#owner = serializers.ReadOnlyField(source='owner.username')

class Meta:
model = User
fields = ('id', 'username', 'meetings',)

class UserListSerializer(serializers.ModelSerializer):
#meetings = serializers.PrimaryKeyRelatedField(many=True, queryset=Meeting.objects.all())

class Meta:
model = User
fields = ('username',)


permissions.py



from rest_framework import permissions

class IsOwnerOrReadOnly(permissions.BasePermission):
def has_object_permission(self, request, view, obj):

# Any permissions are only allowed to the owner of the meeting
return obj.owner == request.user


I overrode IsOwnerOrReadOnly so that only user can view the details of his/her user detail.
And add this to permission_class in views.py.



Then I got this error :



File "/home/tony/env/lib/python3.6/site-packages/rest_framework/views.py" in check_object_permissions
345. if not permission.has_object_permission(request, self, obj):

File "/home/tony/swpp_hw1/meetings/permissions.py" in has_object_permission
15. return obj.owner == request.user

Exception Type: AttributeError at /users/1/
Exception Value: 'User' object has no attribute 'owner'


I tried to add User class in models.py, but again it causes error...
How can solve this issue?










share|improve this question














I am following the tutorial of django Rest Framework. I want to add user-based permission so that only authenticated user can view each user's detail information.
Objective : Anyone can view the UserList, but only owner can view its UserDetail.



models.py



class Meeting(models.Model):
created = models.DateTimeField(auto_now_add=True)
sinceWhen = models.DateTimeField(null=True)
tilWhen = models.DateTimeField(null=True)
owner = models.ForeignKey('auth.User', related_name='meetings', on_delete=models.CASCADE)
#highlighted = models.TextField()

def save(self, *args, **kwargs):
super(Meeting, self).save(*args, **kwargs)


class Meta:
ordering = ('created',)


views.py



from django.contrib.auth.models import User
# User is not created inside models.py

class UserList(generics.ListAPIView):
queryset = User.objects.all()
serializer_class = UserListSerializer

class UserDetail(generics.RetrieveAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly,)
# I added IsOwnerOrReadOnly to make it work, but this is the part where it causes error!


serializers.py



class UserSerializer(serializers.ModelSerializer):
meetings = serializers.PrimaryKeyRelatedField(many=True, queryset=Meeting.objects.all())
#owner = serializers.ReadOnlyField(source='owner.username')

class Meta:
model = User
fields = ('id', 'username', 'meetings',)

class UserListSerializer(serializers.ModelSerializer):
#meetings = serializers.PrimaryKeyRelatedField(many=True, queryset=Meeting.objects.all())

class Meta:
model = User
fields = ('username',)


permissions.py



from rest_framework import permissions

class IsOwnerOrReadOnly(permissions.BasePermission):
def has_object_permission(self, request, view, obj):

# Any permissions are only allowed to the owner of the meeting
return obj.owner == request.user


I overrode IsOwnerOrReadOnly so that only user can view the details of his/her user detail.
And add this to permission_class in views.py.



Then I got this error :



File "/home/tony/env/lib/python3.6/site-packages/rest_framework/views.py" in check_object_permissions
345. if not permission.has_object_permission(request, self, obj):

File "/home/tony/swpp_hw1/meetings/permissions.py" in has_object_permission
15. return obj.owner == request.user

Exception Type: AttributeError at /users/1/
Exception Value: 'User' object has no attribute 'owner'


I tried to add User class in models.py, but again it causes error...
How can solve this issue?







django django-rest-framework django-permissions






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 24 at 5:39









ProbieHProbieH

7610




7610







  • 1





    There is no owner on the User model. There is a reverse relationship named meetings to a Meeting model. > Anyone can view the UserList, but only owner can view its UserDetail. Your permission class just needs to test that obj == request.user. That means that the user that is being looked up is equal to the user that is performing the lookup. The meeting ownership will be handled inherently due to the data model i.e. The user detail view will only show meetings that the looked up user owns.

    – Joshua Taylor Eppinette
    Mar 24 at 6:10












  • 1





    There is no owner on the User model. There is a reverse relationship named meetings to a Meeting model. > Anyone can view the UserList, but only owner can view its UserDetail. Your permission class just needs to test that obj == request.user. That means that the user that is being looked up is equal to the user that is performing the lookup. The meeting ownership will be handled inherently due to the data model i.e. The user detail view will only show meetings that the looked up user owns.

    – Joshua Taylor Eppinette
    Mar 24 at 6:10







1




1





There is no owner on the User model. There is a reverse relationship named meetings to a Meeting model. > Anyone can view the UserList, but only owner can view its UserDetail. Your permission class just needs to test that obj == request.user. That means that the user that is being looked up is equal to the user that is performing the lookup. The meeting ownership will be handled inherently due to the data model i.e. The user detail view will only show meetings that the looked up user owns.

– Joshua Taylor Eppinette
Mar 24 at 6:10





There is no owner on the User model. There is a reverse relationship named meetings to a Meeting model. > Anyone can view the UserList, but only owner can view its UserDetail. Your permission class just needs to test that obj == request.user. That means that the user that is being looked up is equal to the user that is performing the lookup. The meeting ownership will be handled inherently due to the data model i.e. The user detail view will only show meetings that the looked up user owns.

– Joshua Taylor Eppinette
Mar 24 at 6:10












1 Answer
1






active

oldest

votes


















1














Try to change it as:



return obj == request.user 


as object is user you are trying to access and request.user is current authenticated user.






share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55321044%2fhow-to-edit-user-permission-in-django-rest-framework%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    Try to change it as:



    return obj == request.user 


    as object is user you are trying to access and request.user is current authenticated user.






    share|improve this answer



























      1














      Try to change it as:



      return obj == request.user 


      as object is user you are trying to access and request.user is current authenticated user.






      share|improve this answer

























        1












        1








        1







        Try to change it as:



        return obj == request.user 


        as object is user you are trying to access and request.user is current authenticated user.






        share|improve this answer













        Try to change it as:



        return obj == request.user 


        as object is user you are trying to access and request.user is current authenticated user.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 24 at 5:55









        Sergey PugachSergey Pugach

        2,9281622




        2,9281622





























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55321044%2fhow-to-edit-user-permission-in-django-rest-framework%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

            SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

            은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현