Default user Permissions

how can I use this myuser.user_permissions.add(permission) in my views.py file while creating a user to give him a permission like blog.add_post.
I have tried doing user.user_permissions.add(‘blog.add_post’) but it does not work.

We’ll need to see the complete view from your views.py file to see what might not be right. Also, please be more specific as to what you mean by “does not work”. Are you getting an error message? Are you seeing something you’re not expecting? (Or not seeing something you’re expecting to see?)

(Note: When posting code, post it between lines consisting of only three backtick - ` characters. You’ll have one line of ```, followed by your code, followed by another line of ```.)

def signup_client(request,email,otp):
    global current_otp

    if otp == current_otp: 
    
        if request.method == 'POST':

            first_name = request.POST['first_name']
            last_name = request.POST['last_name']
            username = request.POST['username']
            email = email
            password1 = request.POST['password1']
            password2 = request.POST['password2']
            # city = request.POST['city']
            # address = request.POST['address']


            if password1 == password2:

                try:
                    validate_password(password1)
                except:
                    messages.info(request,'password is not strong !!!')
                    return redirect('signup_client',email)


                if User.objects.filter(username=username).exists():
                    messages.info(request,'username is already taken!!!')
                    return redirect('signup_client',email)

                elif User.objects.filter(email=email).exists():
                    messages.info(request,'email is already used!!!')
                    return redirect('signup_client',email)

                else:
                    user = User.objects.create_user(username=username, password=password1, email=email,first_name=first_name,last_name=last_name)
                    user.save()
                    user.user_permissions.add(‘blog.add_post’)
                    client_obj = Client(
                        user = user,
                        # city = city,
                        # address = address,                    
                    )

                    
                    try:  
                        profile_image = request.FILES['profile_image']

                        # img =  fs.save(profile_image.name,profile_image)
                        # img_url = fs.url(img)
                        # print(img_url)
                        
                        client_obj.profile_image = compress_image( profile_image,username+'_image'+'.jpg')
                            
                    
                    except:
                        print('no profile image is selected...')


                    client_obj.save()
                    print('client is created...')
                    print('user is created...')

                
                    user_auth = auth.authenticate(username=username, password=password1)

                    

                    if user_auth is not None:
                        auth.login(request, user_auth)
                        return redirect('/')
            else:
                messages.info(request,'passwords are not matched!!!')
                return redirect('signup_client',email)
        else:
            return render(request, 'signup_client.html')

Are you getting a syntax error on this line? If so, it’s because you have the “fancy quotes” rather than the regular quotes like you have everywhere else in this example such as:

(Note how in your post that the string constants show up in red, but your permission shows up in black.)

This is the correct code

def signup_client(request,email,otp):

    global current_otp

    if otp == current_otp: 

    

        if request.method == 'POST':

            first_name = request.POST['first_name']

            last_name = request.POST['last_name']

            username = request.POST['username']

            email = email

            password1 = request.POST['password1']

            password2 = request.POST['password2']

            # city = request.POST['city']

            # address = request.POST['address']

            if password1 == password2:

                try:

                    validate_password(password1)

                except:

                    messages.info(request,'password is not strong !!!')

                    return redirect('signup_client',email)

                if User.objects.filter(username=username).exists():

                    messages.info(request,'username is already taken!!!')

                    return redirect('signup_client',email)

                elif User.objects.filter(email=email).exists():

                    messages.info(request,'email is already used!!!')

                    return redirect('signup_client',email)

                else:

                    user = User.objects.create_user(username=username, password=password1, email=email,first_name=first_name,last_name=last_name)

                    user.user_permissions.set(['blog.add_blog'])

                    user.save()

                    client_obj = Client(

                        user = user,

                        # city = city,

                        # address = address,                    

                    )

                    

                    try:  

                        profile_image = request.FILES['profile_image']

                        # img =  fs.save(profile_image.name,profile_image)

                        # img_url = fs.url(img)

                        # print(img_url)

                        

                        client_obj.profile_image = compress_image( profile_image,username+'_image'+'.jpg')

                                                

                    except:

                        print('no profile image is selected...')

                    client_obj.save()

                    print('client is created...')

                    print('user is created...')

                

                    user_auth = auth.authenticate(username=username, password=password1)

                    

                    if user_auth is not None:

                        auth.login(request, user_auth)

                        return redirect('/')

            else:

                messages.info(request,'passwords are not matched!!!')

                return redirect('signup_client',email)

        else:

            return render(request, 'signup_client.html')

and the error i am getting is


I saw this from https://docs.djangoproject.com/en/3.1/topics/auth/default/
under the section of Permissions and Authorizations

Yes, it’s looking for the permission object and not the permission string.

You’ll need to do something like:

add_blog_post = Permission.objects.get(codename='add_blog')
user.user_permissions.set([add_blog_post])

If you’ve got more than one app with an “add_blog” permissions name, you can apply an additional filter to the get( for the content type.

(You can see examples of doing something like this down in the Permissions caching and Proxy model sections of the docs.)

I’ll also toss out the opinion that in the long run, you would probably be better off assigning permissions to groups, and then assigning users to groups on an as-appropriate basis. Admittedly, it depends upon how many people need permissions assigned. If your system is in active development and you have hundreds (or thousands) of authenticated users with dozens of apps and hundreds of permissions, you’ll find that using groups is going to make your life a lot easier.

Thank you, can you also tell me how to add a user to group (it would be also helpful if you show me where that is present in the docs because I am unable to find it).

Groups are associated to Users as a many-to-many, just like permissions. Since the relationship is defined on the User side, that means you can do something like user_object.group.add(group_object) or group_object.user_set.add(user_object).