M
M
Maxim Zubenko2018-10-01 14:06:46
Django
Maxim Zubenko, 2018-10-01 14:06:46

How to define an admin, staff, some role (which is defined in the admin panel) in Django, how to assign a role to a freshly registered user?

Immediately I ask you not to swear and not to throw links to https://docs.djangoproject.com/en/2.1/ref/contrib/auth/ , because there are no examples of simple actions that I need and I can’t figure out what to do to get a result.
So I have users:

  • admin - aka superuser
  • personal - just a registered user with a tick in the admin panel next to the staff.
  • manager - the personnel checkbox is checked and the manage role is added (which has permissions to check orders)
  • first, second, test, test2 ... - a crowd of users who are not assigned any rights and roles (because I don't know how to do this), but who are not registered in the admin panel, but in the online store when placing orders, and each of them can log in and everyone can go to their personal account

And in general, all the users listed above can log in, place orders and go to their personal account.
Initially, it was planned to create a series of admin rooms for each role. But I haven't been able to figure this out for a week now. It would seem a simple thing, but nowhere in the Django documentation and in the examples on YouTube, even in English, I can not find a simple thing. (yes, I don't know English and I only use google translator).
What exactly do I need? And you need a simple thing in the views.py file:
# если авторизован, то
    if request.user.is_authenticated:
         if это_суперпользователь:
                # загружаем админку-кабинет суперпользователя (тот который я сам сделал)
                # ...
          elif это_персонал без ролей:
                # загружаем админку-кабинет персонала (другой, но тот который я сам сделал) без каких-либо спец.разрешений
                # ...
          elif это_персонал с ролью manage:
                # загружаем админку-кабинет менеджера (другой, но тот который я сам сделал)
                # ...
          else: 
                # загружаем админку-кабинет простых пользователей (другой, но тот который я сам сделал)
                # ...  кстати это (надеюсь просто через подготовку данных и 
                # return HttpResponseRedirect(reverse('account'))   
                #  и объяснять мне не надо. Мне нужны именно что писать в If-ах?

Well, why can't this be written in the documentation in such a simple, accessible and understandable form? Guys please help me. I'm tired of reading and watching a bunch of unrelated passages.
And if it's not difficult, tell me what to add to registration_view in order to assign a specific role to a newly registered person. Now it's like this:
def registration_view(request):
    form = RegistrationForm(request.POST or None)

    if form.is_valid():
        new_user = form.save(commit=False)
        new_user.username = form.cleaned_data['username']
        new_user.set_password(form.cleaned_data['password']) 
        new_user.email = form.cleaned_data['email']
        new_user.first_name = form.cleaned_data['first_name']
        new_user.last_name = form.cleaned_data['last_name']
        new_user.save()

        login_user = authenticate(request, username=form.cleaned_data['username'], password=form.cleaned_data['password'])

        if login_user:
            login(request, login_user)
            return HttpResponseRedirect(reverse('account'))


    context = {
        'form': form,
    }
    return render(request, 'registration.html', context)

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
Maxim Zubenko, 2018-10-05
@JawsIk

So, as was the topic, I asked two questions. I will answer them in order, so that people can immediately understand what to do in order to get the result. The Django documentation makes me very sad. Everything seems to be there, but in the end there are no examples. And as my one good teacher (not in Django, but in general in programming) said: "Documentation without code examples is just a reference. And if you are not an expert, then such a reference is worthless." Therefore, I will just give two code examples, after which everything will immediately become clear.

def account_view(request):

    cart = Cart()
    cart_id = cart.get_cart_id(request)
    items_in_cart = CartItems.objects.filter(cart_id=cart_id)

    # если не опознан, то дуй на страницу регистрирации
    if not request.user.is_authenticated:
        return HttpResponseRedirect(reverse('registration'))

    # если это суперпользователь
    if request.user.is_superuser:
        template = 'account_admin.html'
    # или если это пользователь с галочкой персонал, а так же принадлежащий группе manager
    elif request.user.is_staff and request.user.groups.filter(name='manager').exists():
        template = 'account_personal_role.html'
    # или если это просто пользователь с галочкой персонал
    elif request.user.is_staff:
        template = 'account_personal.html'
    # или если это пользователь принадлежащий группе manager
    elif request.user.groups.filter(name='manager').exists():
        template = 'account_role.html'
    # иначе все остальные (обычные пользователи)
    else:
        template = 'account.html'

    # сортировка выдачи заказов в обратном порядке (от последнего к первому)    
    list_orders = Order.objects.filter(user=request.user).order_by('-id')
    orders = OrderItems.add_order_info(request, list_orders)

    context = {
        'title': 'Кабинет пользователя',
        'orders': orders,
        'cart': items_in_cart,
        'total_cost': cart_id.total_cost,
    }
    return render(request, template, context=context)

As you can see from the code, there is some sequence here. In particular, if the second condition (the first elif) is omitted below, then incorrect operation is possible, since then a user belonging to the manager group and with a staff checkbox can easily jump into someone else's template (by one condition), so when creating complex conditions, this moment must be taken into account.
...
from django.contrib.auth.models import Group
...

def registration_view(request):

    # (предотвращаем заход по прямой ссылке)
    # если авторизован, то
    if request.user.is_authenticated:
        return HttpResponseRedirect(reverse('account'))

    form = RegistrationForm(request.POST or None)
    if form.is_valid():
        new_user = form.save(commit=False)
        new_user.username = form.cleaned_data['username']
        new_user.set_password(form.cleaned_data['password'])  # вот из-за этой бяки вся засада была у меня с паролями ЗАПОМНИ!!!!!!
        new_user.email = form.cleaned_data['email']
        new_user.first_name = form.cleaned_data['first_name']
        new_user.last_name = form.cleaned_data['last_name']
        new_user.save()

        # после собственно регистрации (сохранения нового) пользователя его можно добавить к группам
        new_user.groups.add(Group.objects.get(name='clients'))
  # new_user.groups.add(Group.objects.get(name='manager'))  # и в ещё одну группу работает тоже

        login_user = authenticate(request, username=form.cleaned_data['username'], password=form.cleaned_data['password'])
        if login_user:
            login(request, login_user)
            return HttpResponseRedirect(reverse('account'))

    context = {
        'title': 'Регистрация',
        'form': form,
    }
    return render(request, 'registration.html', context)

As you can see in the code, after creating a user, he is added to the (previously created) group, and now by going to the admin panel, we can easily check this. In addition, the line with the addition of manager to another group is commented out in the code. If you uncomment it, the user will be added to two groups at once. That. you can add users to several groups at once (if necessary). Naturally, you need to understand that such an addition to the group can be done not only during registration, but seeing this code, making the necessary decision should no longer be difficult.
I hope the code is useful to people.

S
sim3x, 2018-10-01
@sim3x

https://docs.djangoproject.com/en/2.1/ref/contrib/...

K
Konstantin Malyarov, 2018-10-01
@Konstantin18ko

In short, django creates more permissions and groups tables by default.
There are also tables user_permissions, user_groups.
Look for ways to customize them.
get_group_permissions(obj=None)¶
Returns a set of strings representing user permissions added via groups.
Added in Django 1.2.
If obj is specified, returns the permissions for the specified object only.
get_all_permissions(obj=None)
Returns a set of strings representing all user permissions, including groups.
Added in Django 1.2.
If obj is specified, returns the permissions for the specified object only.
request.user.get_all_permissions like so

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question