Home > Software engineering >  How to redirect logged in user with url params?
How to redirect logged in user with url params?

Time:11-01

In my Django project I am trying to make the http://127.0.0.1:8000/ which is the home page to redirect to the Login in Page if user is not logged in however there is a user who is logged in I want http://127.0.0.1:8000/ to become http://127.0.0.1:8000/username/

I have tried different answers but nothing specific lead to this answer: Here is the login view after login:

class LoginView(LoginView):
    template_name = 'login.html'

    def get_success_url(self):
        user=self.request.user.username
        return f'/{user}/'

Here is the login urls:

    path('accounts/login/', LoginView.as_view(redirect_authenticated_user=True,template_name='users/login.html'), name='login'),

Here is the home views:

class home(LoginRequiredMixin, ListView):
    model = Item
    template_name = 'app/home.html'
    context_object_name = 'items'

Here is the app urls:

    path('<str:username>/', home.as_view(), name='home'),

My question:

How to redirect home page to http://127.0.0.1:8000/username/ if user is logged in and if not to login page

CodePudding user response:

You can use settings.LOGIN_URL and settings.LOGIN_REDIRECT_URL so:

class LoginView(LoginView):
    template_name = 'login.html'
    login_url='login'

    def get_success_url(self):
        user=self.request.user.username
        return reverse('home', args=(user))

In settings.py:

LOGIN_URL='some_app_name:login' #Redirect to login page if not logged in.

LOGIN_REDIRECT_URL='some_app_name:home' #Redirect to home page after successful login

It defaults to LOGIN_URL and LOGIN_REDIRECT_URL of settings.py if not specified in views.

Note: It's not a good practice to name same your view with actual authentication view so it should be MyLoginView or anything you can give instead of actual view name.

  • Related