Search code examples
djangoauthenticationhttp-redirectdjango-viewsdjango-authentication

redirect authenticated user at Createview in django


I used CreateView for registration in my project and I want to prevent authenticated user from accessing to the register url instead redirect it to another page.

Can anyone tell me how to do it? here is my register view code:

class RegisterUserView(CreateView):
model = ChatUser
template_name = 'login/registration_page.html'
form_class = UserForm
second_form_class = ProfileForm

Solution

  • You can use UserPassesTestMixin for that:

    class RegisterUserView(UserPassesTestMixin, CreateView):
        model = ChatUser
        template_name = 'login/registration_page.html'
        form_class = UserForm
        second_form_class = ProfileForm
        permission_denied_message = _("You are already registered!")
    
        def test_func(self):
            return self.request.user.is_anonymous