N
N
Neoliz2015-01-03 15:22:32
Django
Neoliz, 2015-01-03 15:22:32

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

3 answer(s)
R
Roman Kitaev, 2015-01-03
@timofeydeys

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'

2) In settings.py add:
AUTH_USER_MODEL = 'core.User' # Where core is your app
3) makemigrations and migrate
If you haven't got to Class Based Views yet, then it's time.
You do something like this, for example:
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)

And all the views that are available only to Vasya are also inherited from this mixin, for example:
class VasyaView(VasyaRequiredMixin, View):
    def get(self, request, *args, **kwargs):
        return HttpResponse('Vasya molodec')

P
Peter, 2015-01-03
@petermzg

For such a task, you need a bunch of decorator + middleware

N
Nail, 2015-01-03
@nail777

Look to the side

from django.contrib.auth.decorators import user_passes_test
@user_passes_test(lambda u: u.is_superuser)

allows you to check if the user passes under his conditions

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question