Akhil Sahu
Akhil Sahu

Reputation: 637

How to use django groups in order to set group permission

I want to use django groups provided in user groups. The django group permissions set in admin panel. Suppose I created two groups teachers and students. I want to set permissions at generic view level. Some views can only be can view or can edit by either student or teacher. These permission were set in django admin as following: enter image description here

Now I created a createview as following:

class CreateQuestionView(LoginRequiredMixin,generic.CreateView):
	model =   Question
	success_url= reverse_lazy('questions:list')
	fields = ['title','description' ]
	def form_valid(self,form):
		form.instance.user = self.request.user
		#self.object.save()
		return super().form_valid(form)

Now I want this view to be accessible by only teacher groups. I cant find a proper way to implement group permission.Something like @group_required may work in this case link but cant find any related documentation. What is correct way to implement this?

Upvotes: 0

Views: 609

Answers (1)

bruno desthuilliers
bruno desthuilliers

Reputation: 77932

You want the PermissionRequiredMixin:

class CreateQuestionView(LoginRequiredMixin, PermissionRequiredMixin, generic.CreateView):
    permission = "yourapp.perm_code_name"
    model =   Question
    success_url= reverse_lazy('questions:list')
    fields = ['title','description' ]
    def form_valid(self,form):
        form.instance.user = self.request.user
        #self.object.save()
        return super().form_valid(form)

Note that you do NOT want to test whether your user belongs to a given group (assuming this group has specific perms) - this is an antipattern. All you care about is whether your user has the required perm, however he has it.

Upvotes: 1

Related Questions