How to redirect logged-in user to a specific page in Django

Question:

Code was not written by me, I am just trying to find a way to redirect a logged-in user if he wants to access a certain page in a Python/Django script. I can actually do it in Templates but as far as I understand this logic should be implemented in Views.

Example: Already logged-in user tries to access to signup page by typing the signup page url/path. In this case, I would like to redirect the user to the homepage (/).

What I tried with very very basic Python and zero Django knowledge?.
Inside the views/auth.py (SignUp class), I try to write a get method and check if user is already authenticated, redirect him to a specific page. And actually it worked for already logged-in users but if a guest/visitor wants to open the sign up page then it returns an error: "views.auth.SignUp didn’t return an HttpResponse object. It returned None instead."

class SignUp(FormView):
    form_class = SignUpForm
    template_name = "xxx/registration/signup.html"
    
    # I added
    def get(self, request, *args, **kwargs):
        if request.user.is_authenticated:
            return redirect('/')
        

    def form_valid(self, form):
        user = form.save(commit=False)
        user.username = form.cleaned_data.get("username").lower()
        user.theme = get_theme_from_cookie(self.request)

        user.save()
        send_email_confirmation(user, user.email)
        notifications.info(
            self.request,
            _(
                "confirmation message.."
            ),
        )
        return redirect("login")

and here is the SignUpForm class

class SignUpForm(UserCreationForm):
    email = forms.EmailField(
        max_length=224,
        help_text=_("required."),
        label=_("e-mail"),
    )
    terms_conditions = forms.BooleanField(required=True)

    class Meta:
        model = User
        fields = (
            "username",
            "email",
            "password1"
        )

I hope this information is enough to guide me or at least give me some hints.

Asked By: TToprak1

||

Answers:

Of course you get an error.
If user.is_authenticated you return redirect(‘/’).

def get(self, request, *args, **kwargs):
    if request.user.is_authenticated:
        return redirect('/')
    # where is else case for guests?

But if user is not authenticated – you return nothing.

Probably it should be:

def get(self, request, *args, **kwargs):
    if request.user.is_authenticated:
        return redirect('/')
    return super().get(request, *args, **kwargs)

By the way, why you don’t use LoginView from django.contrib.auth.views?

Answered By: Maxim Danilov
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.