Home > Enterprise >  How to redirect user from registration page to profile if user is already registered?
How to redirect user from registration page to profile if user is already registered?

Time:12-20

I am using Django class-based views for my project and trying to redirect user from registration view if he is already authenticated. I've done it already with LoginView and it was pretty simple and looked just like adding few lines of code:

class Login(LoginView):
    authentication_form = CustomAuthenticationForm
    redirect_authenticated_user = True
LOGIN_REDIRECT_URL = "core:profile"

So after going to url for login, user ends up at his profile url. Absolutely simple and works perfectly.

However, there is no CBV for registration and therefore CreateView should be used, which doesn`t have any attributes for checking if user is authenticated.

The one method of doing something similar is UserPassesTestMixin, but it only gives me 403 Forbidden if user is authenticated, not redirect.

Here is my current registration view:

class Registration(UserPassesTestMixin, CreateView):
    form_class = RegistrationForm
    template_name = "registration/user_form.html"
    success_url = reverse_lazy("core:profile")

    def test_func(self):
        return self.request.user.is_anonymous

    def form_valid(self, form):
        print(self.kwargs)
        self.object = form.save(commit=True)
        self.object.is_active = True
        self.object.save()

        login(self.request, self.object, backend="core.auth_backend.AuthBackend")
        return HttpResponseRedirect(self.success_url)

Maybe somebody have done it already?

Would be very grateful for every advice!

CodePudding user response:

In your Registration class, add a get method and remove your test_func:

def get(self,request,*args,**kwargs):
    if self.request.user.is_authenticated:
        return HttpResponseRedirect('redirect_url')
    return super().get(request,*args,**kwargs)
  • Related