Register, Login, Logout with django class based views

2.4k views Asked by At

I am trying to make an authentication system with django class based views

What I have tried so far:

This is my views.py file:

from django.shortcuts import render

from django.views import generic

from .forms import UserRegistrationForm

from django.urls import reverse_lazy



class UserCreationView(generic.CreateView):
    form_class = UserRegistrationForm
    template_name = 'registration/register.html'
    success_url = reverse_lazy('login')


This is forms.py file

from django.contrib.auth.forms import UserCreationForm

from django.contrib.auth.models import User


class UserRegistrationForm(UserCreationForm):
    email = forms.EmailField()

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

        widgets = {
            'email': forms.EmailInput(attrs={'class':'input', 'placeholder': 'Email Address'})
    
    }

This the urls.py file:

from django.urls import path

from .views import UserCreationView


urlpatterns = [
    
    path('register/', UserCreationView.as_view(), name = 'register'),

]

Other urls.py file(urls.py file present in project folder)

    path('users/', include(urls)),
    path('users/', include('authentication.urls')),

The problem with this code is Whenever I login I can still login and register by going to the login url(login url in this case:http://localhost:8000/users/login/), How can I restrict user to log in again

1

There are 1 answers

0
erickfis On

I found out that the default LoginView() class on

django.contrib.auth import views 

has a boolean attribute called

redirect_authenticated_user

And I believe this is what you are looking for.

Just look for class LoginView in https://docs.djangoproject.com/en/3.2/topics/auth/default/ and you will see it.