Add Permission to Django Admin - python

Last Month i posted question on stackoverflow and on Django-Users group on G+ and on django website too. But i didn't find any answer that can solve my problem. What i want to do is to add new permission named as view in django admin panel, so user can only view data!. I also followed different patches from django website and tried django-databrowse but nothing works as expected. I then finally decide to edit views of auth/admin. Now what i am going to do is to add view permission like:
1. Added 'view' to default permission list
#./contrib/auth/management/init.py
def _get_all_permissions(opts):
"Returns (codename, name) for all permissions in the given opts."
perms = []
for action in ('add', 'change', 'delete', 'view'):
perms.append((_get_permission_codename(action, opts), u'Can %s %s' % (action, opts.verbose_name_raw)))
return perms + list(opts.permissions)
2. Test the 'view' permission is added to all models
run manage.py syncdb
After this i can assign only view permission to user. Now this view permission must work too. So i am writing this code: in view.py of django-admin
for per in request.user.user_permissions_all():
print per
This code prints permissions assigned to login user like auth | permission | can view department etc
Now i can get permission type and model name by splitting this sentence. I will get all the model name of application and will match that which data must b visible. This is again not what i really need but can work.
So my question is :
* Is this is what i should do or is there any other way too. I just want a solution that must works as expected. Need Your Assistance *

Adding 'view' permission to default permissions list
Your solution works, but you should really avoid editing source code if possible. There's a few ways to accomplish this within the framework:
1. Add the permission during post_syncdb():
In a file under your_app/management/
from django.db.models.signals import post_syncdb
from django.contrib.contenttypes.models import ContentType
from django.contrib.auth.models import Permission
def add_view_permissions(sender, **kwargs):
"""
This syncdb hooks takes care of adding a view permission too all our
content types.
"""
# for each of our content types
for content_type in ContentType.objects.all():
# build our permission slug
codename = "view_%s" % content_type.model
# if it doesn't exist..
if not Permission.objects.filter(content_type=content_type, codename=codename):
# add it
Permission.objects.create(content_type=content_type,
codename=codename,
name="Can view %s" % content_type.name)
print "Added view permission for %s" % content_type.name
# check for all our view permissions after a syncdb
post_syncdb.connect(add_view_permissions)
Whenever you issue a 'syncdb' command, all content types can be
checked to see if they have a 'view' permission, and if not, create
one.
SOURCE: The Nyaruka Blog
2. Add the permission to the Meta permissions option:
Under every model you would add something like this to its Meta options:
class Pizza(models.Model):
cheesiness = models.IntegerField()
class Meta:
permissions = (
('view_pizza', 'Can view pizza'),
)
This will accomplish the same as 1 except you have to manually add it to each class.
3. NEW in Django 1.7, Add the permission to the Meta default_permissions option:
In Django 1.7 they added the default_permissions Meta option. Under every model you would add 'view' to the default_permissions option:
class Pizza(models.Model):
cheesiness = models.IntegerField()
class Meta:
default_permissions = ('add', 'change', 'delete', 'view')
Test the 'view' permission is added to all models
As for testing the whether a user has the permission, you can test on the has_perm() function. For example:
user.has_perm('appname.view_pizza') # returns True if user 'Can view pizza'

Related

Custom permissions on Django group form

I've added some custom permissions to my Post model.
I've also created a form to add/edit groups with only this custom permissions:
class GroupFornm(forms.ModelForm):
permissions = forms.MultipleChoiceField(choices=Post._meta.permissions)
class Meta:
model = Group
fields = '__all__'
It works because I can see and select only my custom permissions but when I try to save the form I got the error:
invalid literal for int() with base 10: 'can_view'
What am I doing wrong? It seems that this form field waits for (int, str) pair but documentation says that as usually, (str, str) should work.
Edit
Post._meta.permissions:
(('can_view', 'Can see tickets'), ('can_edit', 'Can edit tickets'), ('can_delete', 'Can delete tickets'), ('can_create', 'Can add new tickets'))
The problem is not really related to the form itself, but the fact that you somehow need to translate those permissions into Permission objects that should be stored in the Group instance (the one that this ModelForm is managing).
I think displaying the options is not a problem. But if a user later for example performs a POST request, with the options (like can_write), then the question is how the Form should translate these into Permission objects (or the primary keys of Permission objects).
In that case you need to coerce the name of the permissions to Permission objects, or the ids of Permission objects. We can for example use a TypedMultipleChoiceField, and coerce with:
def get_permission_from_name(name):
return Permission.objects.get(name=name)
class GroupFornm(forms.ModelForm):
permissions = forms.TypedMultipleChoiceField(
choices=Post._meta.permissions,
coerce=get_permission_from_name,
)
class Meta:
model = Group
fields = '__all__'
Note that the above is not really a very efficient implementation, since it requires a query for every value send. Furthermore in case no permission with that name exists, then this will raise an error.
If you want to construct Permissions on the fly (in case these are not yet constructed), then you can change the function to:
def get_permission_from_name(name):
return Permission.objects.get_or_create(
name=name,
defaults={
'content_type': ContentType.objects.get_for_model(Post),
'codename': name
}
)

adding custom permission through django-admin, while server is running

In Django-admin, Is it possible to make feature so that admin can create/edit/delete certain permission through django-admin while the server is running?
In django-admin I want the permission can be listed, with edit create and delete feature
Using permission in Meta subclass of models class will create custom permission through migrate script.
taken from https://docs.djangoproject.com/en/1.8/topics/auth/customizing/#custom-permissions
class Task(models.Model):
...
class Meta:
permissions = (
("view_task", "Can see available tasks"),
("change_task_status", "Can change the status of tasks"),
("close_task", "Can remove a task by setting its status as closed"),
)
This will insert values on auth_permission (and django_content_type)
But that requires database migrations, which means unlikely be done by user (Admin) but by the developer instead. And I believe it is necessary for application to be able to manage permission, creating, editing, deleting while the server is running.
So what is the best practice to make this functionality with Django? Should I keep using migrate & create them all in each model and to reload server everytime we implement new permission or feature in general? thankyou
You can register the Permission model to admin view:
from django.contrib.auth.models import Permission
from django.contrib import admin
admin.site.register(Permission)
The code can be anywhere where it gets executed, but admin.py of your application could be an intuitive place to stick it in. After this, you will be able to view, edit and remove the permissions.
You also need to select_related because it will result in a bunch of SQL queries
from django.contrib import admin
from django.contrib.auth.models import Permission
#admin.register(Permission)
class PermissionAdmin(admin.ModelAdmin):
def get_queryset(self, request):
qs = super().get_queryset(request)
return qs.select_related('content_type')

django-guardian how to make object inherit permissions of related object?

I got two models:
class ContactGroup(models.Model):
name = models.CharField(max_length=40)
class Meta:
permissions=(('view_group_contacts', 'View contacts from group'))
class Contact(models.Model):
name = models.CharField(max_length=40)
group = models.ForeignKey(ContactGroup)
class Meta:
permissions=(('view_contact', 'View contact'))
How can I make django guardian consider ContactGroup permissions when I'm for example doing `get_objects_for_user(User, 'appname.view_contact) but still retain option for changing permission on individual Contact?(not for excluding, only to give permission to view single contact when user don't have the permission for whole group)
Sorry, such behaviour is not supported by django-guardian. As for has_perm - it would be extremely inefficient to use it for querysets as we would need to perform >=1 query for each row in a table.
You could however perform get_objects_for_user firstly for ContactGroup, then for Contact and extend last queryset with results from the first one. Something like:
contact_groups = get_objects_for_user(user, 'appname.view_group_contacts', ContactGroup)
contacts = get_objects_for_user(user, 'appname.view_contact', Contact)
There is still problem of merging those but well, it's possible.
Very ugly workaround, it does not take for account changes in individual objects (it resets all permission to ContactGroup permissions if remove= False). But It can be rewritten to preserve changes if needed. I plan to attach it to "Sync Permissions with group" button so it will be fired only at user request. Main pro is its working with get_objects_for_user as intended.
def syncPerms(source, remove=False):
if not isinstance(source, ContactGroup):
return False
contacts= source.client_set.all()
user_perms=get_users_with_perms(source, attach_perms=True)
for contact in contacts:
for user, perm in user_perms.iteritems():
if u'view_group_contacts' in perm:
assign_perm('view_contact', user,client)
else:
if remove:
remove_perm('view_contact', user, client)

When to programmatically create custom Django permissions?

The permission/authentication documentation for Django 1.4 provides the following snippet for creating custom permissions programmatically:
Edit: (I would like to employ this for permissions that are not necessarily linked to a specific model class, but more general permissions that span multiple types.)
from django.contrib.auth.models import Group, Permission
from django.contrib.contenttypes.models import ContentType
content_type = ContentType.objects.get(app_label='myapp', model='BlogPost')
permission = Permission.objects.create(codename='can_publish',
name='Can Publish Posts',
content_type=content_type)
Source
My question is where this code should be placed. Obviously these should only be created once, but I don't want to have to do it in the shell. It seems like this should be stored in a file somewhere. (For documentation sake.)
Usually it is enough to just add the needed permissions to the corresponding model class using the permissions meta attribute.
This is from the official documentation:
class Task(models.Model):
...
class Meta:
permissions = (
("view_task", "Can see available tasks"),
("change_task_status", "Can change the status of tasks"),
("close_task", "Can remove a task by setting its status as closed"),
)

Remove (or hide) default Permissions from Django

I'm developing a Django app that will have two administration backends. One for daily use by "normal" users and the default one for more advanced tasks and for the developers.
The application uses some custom permissions but none of the default ones. So I'm currently looking for a way to remove the default permissions, or at least a way to hide them from the "daily" admin backend without large modifications.
UPDATE: Django 1.7 supports the customization of default permissions
Original Answer
The following is valid for Django prior to version 1.7
This is standard functionality of the auth contrib application.
It handles the post_syncdb signal and creates the permissions (the standard 3: add, change, delete, plus any custom ones) for each model; they are stored in the auth_permission table in the database.
So, they will be created each time you run the syncdb management command
You have some choices. None is really elegant, but you can consider:
Dropping the auth contrib app and provide your own authentication backend.
Consequences -> you will lose the admin and other custom apps built on top of the auth User model, but if your application is highly customized that could be an option for you
Overriding the behaviour of the post_syncdb signal inside the auth app (inside \django\contrib\auth\management__init__.py file)
Consequences -> be aware that without the basic permissions the Django admin interface won't be able to work (and maybe other things as well).
Deleting the basic permissions (add, change, delete) for each model inside the auth_permission table (manually, with a script, or whatever).
Consequences -> you will lose the admin again, and you will need to delete them each time you run syncdb.
Building your own Permission application/system (with your own decorators, middlewares, etc..) or extending the existing one.
Consequences -> none, if you build it well - this is one of the cleanest solutions in my opinion.
A final consideration: changing the contrib applications or Django framework itself is never considered a good thing: you could break something and you will have hard times if you will need to upgrade to a newer version of Django.
So, if you want to be as clean as possibile, consider rolling your own permission system, or extending the standard one (django-guardian is a good example of an extension to django permissions). It won't take much effort, and you can build it the way it feels right for you, overcoming the limitations of the standard django permission system. And if you do a good work, you could also consider to open source it to enable other people using/improving your solution =)
I struggled with this same problem for a while and I think I've come up with a clean solution. Here's how you hide the permissions for Django's auth app:
from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
from django import forms
from django.contrib.auth.models import Permission
class MyGroupAdminForm(forms.ModelForm):
class Meta:
model = MyGroup
permissions = forms.ModelMultipleChoiceField(
Permission.objects.exclude(content_type__app_label='auth'),
widget=admin.widgets.FilteredSelectMultiple(_('permissions'), False))
class MyGroupAdmin(admin.ModelAdmin):
form = MyGroupAdminForm
search_fields = ('name',)
ordering = ('name',)
admin.site.unregister(Group)
admin.site.register(MyGroup, MyGroupAdmin)
Of course it can easily be modified to hide whatever permissions you want. Let me know if this works for you.
A new feature introduced in Django 1.7 is the ability to define the default permissions. As stated in the documentation if you set this to empty none of the default permissions will be created.
A working example would be:
class Blar1(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=255, unique = True, blank = False, null = False, verbose_name= "Name")
class Meta:
default_permissions = ()
ShadowCloud gave a good rundown. Here's a simple way to accomplish your goal.
Add these line in your admin.py:
from django.contrib.auth.models import Permission
admin.site.register(Permission)
You can now add/change/delete permissions in the admin. Remove the unused ones and when you have what you want, go back and remove these two lines from admin.py.
As was mentioned by others, a subsequent syncdb will put everything back.
Built on top of the solution by #pmdarrow, I've come up with a relatively clean solution to patch the Django admin views.
See: https://gist.github.com/vdboor/6280390
It extends the User and Group admin to hide certain permissions.
You can't easily delete those permissions (so that syncdb won't put them back), but you can hide them from the admin interface. The idea is, as described by others, to override the admin forms but you have to do this for both users and groups.
Here is the admin.py with the solution:
from django import forms
from django.contrib import admin
from django.contrib.auth.models import Permission
from django.contrib.auth.models import User, Group
from django.contrib.auth.admin import GroupAdmin, UserAdmin
from django.contrib.auth.forms import UserChangeForm
#
# In the models listed below standard permissions "add_model", "change_model"
# and "delete_model" will be created by syncdb, but hidden from admin interface.
# This is convenient in case you use your own set of permissions so the list
# in the admin interface wont be confusing.
# Feel free to add your models here. The first element is the app name (this is
# the directory your app is in) and the second element is the name of your model
# from models.py module of your app (Note: both names must be lowercased).
#
MODELS_TO_HIDE_STD_PERMISSIONS = (
("myapp", "mymodel"),
)
def _get_corrected_permissions():
perms = Permission.objects.all()
for app_name, model_name in MODELS_TO_HIDE_STD_PERMISSIONS:
perms = perms.exclude(content_type__app_label=app_name, codename='add_%s' % model_name)
perms = perms.exclude(content_type__app_label=app_name, codename='change_%s' % model_name)
perms = perms.exclude(content_type__app_label=app_name, codename='delete_%s' % model_name)
return perms
class MyGroupAdminForm(forms.ModelForm):
class Meta:
model = Group
permissions = forms.ModelMultipleChoiceField(
_get_corrected_permissions(),
widget=admin.widgets.FilteredSelectMultiple(('permissions'), False),
help_text = 'Hold down "Control", or "Command" on a Mac, to select more than one.'
)
class MyGroupAdmin(GroupAdmin):
form = MyGroupAdminForm
class MyUserChangeForm(UserChangeForm):
user_permissions = forms.ModelMultipleChoiceField(
_get_corrected_permissions(),
widget=admin.widgets.FilteredSelectMultiple(('user_permissions'), False),
help_text = 'Hold down "Control", or "Command" on a Mac, to select more than one.'
)
class MyUserAdmin(UserAdmin):
form = MyUserChangeForm
admin.site.unregister(Group)
admin.site.register(Group, MyGroupAdmin)
admin.site.unregister(User)
admin.site.register(User, MyUserAdmin)
If you are creating your own user management backend and only want to show your custom permissions you can filter out the default permissions by excluding permission with a name that starts with "Can".
WARNING:
You must remember not to name your permissions starting with "Can"!!!!
If they decide to change the naming convention this might not work.
With credit to pmdarrow this is how I did this in my project:
from django.contrib.auth.forms import UserChangeForm
from django.contrib.auth.models import Permission
from django.contrib import admin
class UserEditForm(UserChangeForm):
class Meta:
model = User
exclude = (
'last_login',
'is_superuser',
'is_staff',
'date_joined',
)
user_permissions = forms.ModelMultipleChoiceField(
Permission.objects.exclude(name__startswith='Can'),
widget=admin.widgets.FilteredSelectMultiple(_('permissions'), False))
If you want to prevent Django from creating permissions, you can block the signals from being sent.
If you put this into a management/init.py in any app, it will bind to the signal handler before the auth framework has a chance (taking advantage of the dispatch_uid debouncing).
from django.db.models import signals
def do_nothing(*args, **kwargs):
pass
signals.post_syncdb.connect(do_nothing, dispatch_uid="django.contrib.auth.management.create_permissions")
signals.post_syncdb.connect(do_nothing, dispatch_uid="django.contrib.auth.management.create_superuser")

Categories

Resources