Assigning user permissions with post_save signal












3















I have a custom User model called EmailUser and I'm trying to assign a custom model permission on post_save. I have the following signal in models.py



@receiver(post_save, sender=EmailUser)
def assign_permissions(sender, **kwargs):
emailUser = kwargs["instance"]
if kwargs["created"]:
permission = Permission.objects.get(name='Can view polls')
emailUser.user_permissions.add(permission)
print emailUser.user_permissions.all()


The print statement returns the expected: [<Permission: polls | poll | Can view polls>] but when I look at the user in admin the permission is not selected and when I check it in shell, the permissions are empty.










share|improve this question




















  • 1





    Could you try emailUser.save() before adding the permission to the user.

    – pythonista
    May 11 '16 at 23:26











  • @pythonista: Just tried that. Same exact behavior.

    – oppositeday
    May 11 '16 at 23:48











  • @oppositeday did you figure out a solution? I'm having a similar problem.

    – newdimension
    May 7 '17 at 23:05











  • @newdimension: Sadly, no. I ended up having to use a workaround.

    – oppositeday
    May 10 '17 at 16:32
















3















I have a custom User model called EmailUser and I'm trying to assign a custom model permission on post_save. I have the following signal in models.py



@receiver(post_save, sender=EmailUser)
def assign_permissions(sender, **kwargs):
emailUser = kwargs["instance"]
if kwargs["created"]:
permission = Permission.objects.get(name='Can view polls')
emailUser.user_permissions.add(permission)
print emailUser.user_permissions.all()


The print statement returns the expected: [<Permission: polls | poll | Can view polls>] but when I look at the user in admin the permission is not selected and when I check it in shell, the permissions are empty.










share|improve this question




















  • 1





    Could you try emailUser.save() before adding the permission to the user.

    – pythonista
    May 11 '16 at 23:26











  • @pythonista: Just tried that. Same exact behavior.

    – oppositeday
    May 11 '16 at 23:48











  • @oppositeday did you figure out a solution? I'm having a similar problem.

    – newdimension
    May 7 '17 at 23:05











  • @newdimension: Sadly, no. I ended up having to use a workaround.

    – oppositeday
    May 10 '17 at 16:32














3












3








3








I have a custom User model called EmailUser and I'm trying to assign a custom model permission on post_save. I have the following signal in models.py



@receiver(post_save, sender=EmailUser)
def assign_permissions(sender, **kwargs):
emailUser = kwargs["instance"]
if kwargs["created"]:
permission = Permission.objects.get(name='Can view polls')
emailUser.user_permissions.add(permission)
print emailUser.user_permissions.all()


The print statement returns the expected: [<Permission: polls | poll | Can view polls>] but when I look at the user in admin the permission is not selected and when I check it in shell, the permissions are empty.










share|improve this question
















I have a custom User model called EmailUser and I'm trying to assign a custom model permission on post_save. I have the following signal in models.py



@receiver(post_save, sender=EmailUser)
def assign_permissions(sender, **kwargs):
emailUser = kwargs["instance"]
if kwargs["created"]:
permission = Permission.objects.get(name='Can view polls')
emailUser.user_permissions.add(permission)
print emailUser.user_permissions.all()


The print statement returns the expected: [<Permission: polls | poll | Can view polls>] but when I look at the user in admin the permission is not selected and when I check it in shell, the permissions are empty.







django django-authentication django-signals






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited May 11 '16 at 0:43









trantu

909615




909615










asked May 10 '16 at 22:08









oppositedayoppositeday

4113




4113








  • 1





    Could you try emailUser.save() before adding the permission to the user.

    – pythonista
    May 11 '16 at 23:26











  • @pythonista: Just tried that. Same exact behavior.

    – oppositeday
    May 11 '16 at 23:48











  • @oppositeday did you figure out a solution? I'm having a similar problem.

    – newdimension
    May 7 '17 at 23:05











  • @newdimension: Sadly, no. I ended up having to use a workaround.

    – oppositeday
    May 10 '17 at 16:32














  • 1





    Could you try emailUser.save() before adding the permission to the user.

    – pythonista
    May 11 '16 at 23:26











  • @pythonista: Just tried that. Same exact behavior.

    – oppositeday
    May 11 '16 at 23:48











  • @oppositeday did you figure out a solution? I'm having a similar problem.

    – newdimension
    May 7 '17 at 23:05











  • @newdimension: Sadly, no. I ended up having to use a workaround.

    – oppositeday
    May 10 '17 at 16:32








1




1





Could you try emailUser.save() before adding the permission to the user.

– pythonista
May 11 '16 at 23:26





Could you try emailUser.save() before adding the permission to the user.

– pythonista
May 11 '16 at 23:26













@pythonista: Just tried that. Same exact behavior.

– oppositeday
May 11 '16 at 23:48





@pythonista: Just tried that. Same exact behavior.

– oppositeday
May 11 '16 at 23:48













@oppositeday did you figure out a solution? I'm having a similar problem.

– newdimension
May 7 '17 at 23:05





@oppositeday did you figure out a solution? I'm having a similar problem.

– newdimension
May 7 '17 at 23:05













@newdimension: Sadly, no. I ended up having to use a workaround.

– oppositeday
May 10 '17 at 16:32





@newdimension: Sadly, no. I ended up having to use a workaround.

– oppositeday
May 10 '17 at 16:32












1 Answer
1






active

oldest

votes


















0














I had exactly the same problem, I tried to use post_save|pre_save|redefining save() model method|redefining model_save() method in admin.py file, but I didn't get the expected behavior(don't see selected permissions in the admin interface)



So I started investigating this question and found in django.contrib.admin.options file, ModelAdmin class, _changeform_view method the next code:



self.save_model(request, new_object, form, not add)
self.save_related(request, form, formsets, not add)


So firstly instance is saved by save_model and then permissions are rewritten by save_related



So I just redefined changeform_view in my UserAdmin class



My redefined code listing is the next:



def changeform_view(self, request, object_id=None, form_url='', extra_context=None):

to_field = request.POST.get(TO_FIELD_VAR, request.GET.get(TO_FIELD_VAR))
obj = self.get_object(request, unquote(object_id), to_field)
user = get_object_or_404(User, id=obj.id)
if user.is_lab_director:
permission = Permission.objects.get(name='Can change job')
user.user_permissions.add(permission)
else:
user.user_permissions.clear()

with transaction.atomic(using=router.db_for_write(self.model)):
return self._changeform_view(request, object_id, form_url, extra_context)


I hove this help someone to solve such question






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%2f37149794%2fassigning-user-permissions-with-post-save-signal%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









    0














    I had exactly the same problem, I tried to use post_save|pre_save|redefining save() model method|redefining model_save() method in admin.py file, but I didn't get the expected behavior(don't see selected permissions in the admin interface)



    So I started investigating this question and found in django.contrib.admin.options file, ModelAdmin class, _changeform_view method the next code:



    self.save_model(request, new_object, form, not add)
    self.save_related(request, form, formsets, not add)


    So firstly instance is saved by save_model and then permissions are rewritten by save_related



    So I just redefined changeform_view in my UserAdmin class



    My redefined code listing is the next:



    def changeform_view(self, request, object_id=None, form_url='', extra_context=None):

    to_field = request.POST.get(TO_FIELD_VAR, request.GET.get(TO_FIELD_VAR))
    obj = self.get_object(request, unquote(object_id), to_field)
    user = get_object_or_404(User, id=obj.id)
    if user.is_lab_director:
    permission = Permission.objects.get(name='Can change job')
    user.user_permissions.add(permission)
    else:
    user.user_permissions.clear()

    with transaction.atomic(using=router.db_for_write(self.model)):
    return self._changeform_view(request, object_id, form_url, extra_context)


    I hove this help someone to solve such question






    share|improve this answer




























      0














      I had exactly the same problem, I tried to use post_save|pre_save|redefining save() model method|redefining model_save() method in admin.py file, but I didn't get the expected behavior(don't see selected permissions in the admin interface)



      So I started investigating this question and found in django.contrib.admin.options file, ModelAdmin class, _changeform_view method the next code:



      self.save_model(request, new_object, form, not add)
      self.save_related(request, form, formsets, not add)


      So firstly instance is saved by save_model and then permissions are rewritten by save_related



      So I just redefined changeform_view in my UserAdmin class



      My redefined code listing is the next:



      def changeform_view(self, request, object_id=None, form_url='', extra_context=None):

      to_field = request.POST.get(TO_FIELD_VAR, request.GET.get(TO_FIELD_VAR))
      obj = self.get_object(request, unquote(object_id), to_field)
      user = get_object_or_404(User, id=obj.id)
      if user.is_lab_director:
      permission = Permission.objects.get(name='Can change job')
      user.user_permissions.add(permission)
      else:
      user.user_permissions.clear()

      with transaction.atomic(using=router.db_for_write(self.model)):
      return self._changeform_view(request, object_id, form_url, extra_context)


      I hove this help someone to solve such question






      share|improve this answer


























        0












        0








        0







        I had exactly the same problem, I tried to use post_save|pre_save|redefining save() model method|redefining model_save() method in admin.py file, but I didn't get the expected behavior(don't see selected permissions in the admin interface)



        So I started investigating this question and found in django.contrib.admin.options file, ModelAdmin class, _changeform_view method the next code:



        self.save_model(request, new_object, form, not add)
        self.save_related(request, form, formsets, not add)


        So firstly instance is saved by save_model and then permissions are rewritten by save_related



        So I just redefined changeform_view in my UserAdmin class



        My redefined code listing is the next:



        def changeform_view(self, request, object_id=None, form_url='', extra_context=None):

        to_field = request.POST.get(TO_FIELD_VAR, request.GET.get(TO_FIELD_VAR))
        obj = self.get_object(request, unquote(object_id), to_field)
        user = get_object_or_404(User, id=obj.id)
        if user.is_lab_director:
        permission = Permission.objects.get(name='Can change job')
        user.user_permissions.add(permission)
        else:
        user.user_permissions.clear()

        with transaction.atomic(using=router.db_for_write(self.model)):
        return self._changeform_view(request, object_id, form_url, extra_context)


        I hove this help someone to solve such question






        share|improve this answer













        I had exactly the same problem, I tried to use post_save|pre_save|redefining save() model method|redefining model_save() method in admin.py file, but I didn't get the expected behavior(don't see selected permissions in the admin interface)



        So I started investigating this question and found in django.contrib.admin.options file, ModelAdmin class, _changeform_view method the next code:



        self.save_model(request, new_object, form, not add)
        self.save_related(request, form, formsets, not add)


        So firstly instance is saved by save_model and then permissions are rewritten by save_related



        So I just redefined changeform_view in my UserAdmin class



        My redefined code listing is the next:



        def changeform_view(self, request, object_id=None, form_url='', extra_context=None):

        to_field = request.POST.get(TO_FIELD_VAR, request.GET.get(TO_FIELD_VAR))
        obj = self.get_object(request, unquote(object_id), to_field)
        user = get_object_or_404(User, id=obj.id)
        if user.is_lab_director:
        permission = Permission.objects.get(name='Can change job')
        user.user_permissions.add(permission)
        else:
        user.user_permissions.clear()

        with transaction.atomic(using=router.db_for_write(self.model)):
        return self._changeform_view(request, object_id, form_url, extra_context)


        I hove this help someone to solve such question







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 22 '18 at 12:59









        Vasily VlasovVasily Vlasov

        13512




        13512
































            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%2f37149794%2fassigning-user-permissions-with-post-save-signal%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

            android studio warns about leanback feature tag usage required on manifest while using Unity exported app?

            SQL update select statement

            WPF add header to Image with URL pettitions [duplicate]