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

            How to preserve electronics (computers, tablets and phones) for hundreds of years Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) The network's official Twitter account is up and running again. What content…How might modern humans leave a message for 50,000 years?How would an aquatic race develop computers?How do we make computers care for human life?Keeping supplies for 1000 yearsWhat will cell phones become in 100 years?What body armor protects against a laser?Could a society attain 1800s technology if limited to using copper and bronze?Electricity power (magic) and electronicsScavenging metal resources in post-apocalypse after 100 yearsWhy would precursors create devices that can survive and still work after hundreds of years?

            155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해

            Convert JSON to MapSimplest way to convert a string representing JSON array into Java array List of key value pairsHow to take String JSON values into HashMapConvert a JSON String to a HashMapCreating BSON object from JSON stringJSONObject - How to get a value ?Better Map ConstructorReading JSON from Url javaUpdate columns if input values are not null otherwise ignore and keep the existing values of column in databaseHow to store object represented as Json string into Couchbase Lite?Go JSON into MapHow do I efficiently iterate over each entry in a Java Map?Sort a Map<Key, Value> by valuesHow to round a number to n decimal places in JavaCan comments be used in JSON?How do I read / convert an InputStream into a String in Java?How can I pretty-print JSON in a shell script?What is the correct JSON content type?How can I deserialize JSON to a simple Dictionary<string,string> in ASP.NET?Why does Google prepend while(1); to their JSON responses?Parse JSON in JavaScript?