Answer the question
In order to leave comments, you need to log in
How to write your own decorator in django?
Good evening! Need help with following issue. I recently started learning python, and python too.
There is a task, you need to write your own decorator, but no matter how much I googled, I did not understand how to implement my task. Help a beginner, and a detailed description. Please do not rush and only answer if you want to help.
In general, there is a decorator login_required
I have a standard User table and my table is linked by FR typeUser. There are three types of user. And I need my own decorator for each type. What would he compare the type of the user through request, and pass to the function if the type matches.
How to do it?
Answer the question
In order to leave comments, you need to log in
To begin with, expand the user model so as not to crutch with all sorts of typeUser tables:
1) In the main app (I usually have a core) create a User model inherited from AbstractUser:
from django.db import models
from django.contrib.auth.models import AbstractUser
# Это лучше перенести в отдельный файл consts.py
USER_ADMIN = 'adm'
USER_MANAGER = 'mng'
USER_VASYA = 'vas'
USER_TYPES = (
(USER_ADMIN, 'Администратор'),
(USER_MANAGER, 'Менеджер'),
(USER_VASYA, 'Вася'),
)
class User(AbstractUser):
type = models.CharField(max_length=3, choices=USER_TYPES)
class Meta(AbstractUser.Meta):
swappable = 'AUTH_USER_MODEL'
from django.core.exceptions import PermissionDenied
# тут импорт USER_VASYA
class VasyaRequiredMixin(object):
def dispatch(self, request, *args, **kwargs):
if request.user.type != USER_VASYA:
raise PermissionDenied
return super(VasyaRequiredMixin, self).dispatch(request, *args, **kwargs)
class VasyaView(VasyaRequiredMixin, View):
def get(self, request, *args, **kwargs):
return HttpResponse('Vasya molodec')
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question