Search code examples
djangodjango-viewsdjango-templatesdjango-usersdjango-login

Django Custom Login


I want a Loginpage which redirects User based on groups AND their username pk. Like Staff has a dashboard which they can see all the work from employees while employees are redirected to their own page based on their pk

I made something with class based views and it works. But Staff are redirected to an empty page where they can click on a dashboard button which redirects them there. This dashboard button shows only if they are in a specific group restricted by a for loop in the template.

And when employers try to go manually to that dashboard they see an empty page bc of the for loop for staff member but besides the horrible security I know that it must be somehow possible to do an if condition. But no matter where I look or what I try thats the only result I have.

Does anybody has an idea ? template:

{% for group in request.user.groups.all %} {% if group.name == 'Personalverwaltung' %}

    <li><a href="{% url 'Dashboard' %}">dashboard</a></li>
    {% endif %}
    {% endfor %}

{% for group in request.user.groups.all %} {% if group.name == 'Personalverwaltung' %}

html

{% endif %} {% endfor %}

View:

class Einloggen(LoginView): template_name = 'SCHUK/Einloggen.html' fields ='all' redirect_authenticated_user = True

def get_success_url(self):
    return reverse('Schulverzeichnis', args=[self.request.user.pk])

urls:

path('Schulverzeichnis/<int:pk>', Schulverzeichnis.as_view(), name='Schulverzeichnis'),

And now if I register a user to his template view the redirection works while when I register staff I just dont give them a view and when they login they have a blank page with dashboard link. But I mean thats not best practise to redirect users


Solution

  • You need to do it in get_success_url(self) method:

    def get_success_url(self):
        if self.request.user.groups.filter(name='Personalverwaltung').exists():
             return reverse('Dashboard')
        else: #for users that are not members of Personalverwaltung group
          return reverse('index')