You often come to situations where you may need a view to be accessed only by certain group of users. For example you have the app that has two groups of users. One can search and another one can Index files. Simplest approach is to use Groups here.
In fact you may use permissions in case your app will have several unique users that might do some stuff. In general best approach is to use Group to specify type of users and Permission to specify the role of users in this group. So if you will have Group called 'search' and it will have permission with name, say 'search stuff'. So when you will call:
will print something like 'search stuff'. If this request user is in group 'search'. Because Django User is m2m related to Group and Permission objects. So we can create a Group full of Permissions and User within that group will have all those permissions.
Now that we had main idea in head and may think about some tasty and handy stuff for our "most used" needs.
Group required view decorator.
We have several methods/ways here. Brad Montgomery suggested that we will use user passes test decorator. In his Blog. I'll copy and modify his example a bit to use group name used in this article.
This stuff may suite you well. BUT imho there is much tastier approach.
There is one view decorator. Django Snippets. It is called view decorator and you can use it like so:
And in case stuff will disappear in the net. Here is the snippet itself:
Nice and simple isn't it? If takes a grop name from the list that you provide him and checks user authorship in there.
Programmatically creating groups and users.
Note that Django docs is always the best explanation. But sometimes insufficient for new byes.
Let's start from adding a group. You may use groups to define roles of users.
Now that we have groups set up and ready to go we can setup permissions for them. Django associates permission with model.Models object, but not it's instance. So you need to select a model to operate and apply a content type to it. Note you may even inven your own content type for those needs.
We have earlier defined 2 permissions and can now apply them to groups we have created:
Now we can use our request user to apply groups to him:
Now it came to:
You can use it wherever you like this. For e.g. in templates:
Hope some stuff here helps you like it did to me. May the code be with you! Comment me ;)