[Django] I want to log in automatically after new registration

Introduction

New registration and login are the basic functions when creating a website. After completing the new registration, I wanted to omit the work of entering the necessary items on the login screen again, so I investigated the method.

Premise

The project structure is as follows. The setting directory is config, and the application directory is created in app and accounts.

.
├── accounts
│   ├── __init__.py
│   ├── admin.py
│   ├── apps.py
│   ├── forms.py
│   ├── migrations
│   ├── models.py
│   ├── tests.py
│   ├── urls.py
│   └── views.py
├── config
│   ├── __init__.py
│   ├── asgi.py
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
├── manage.py
├── app
│   ├── __init__.py
│   ├── apps.py
│   ├── forms.py
│   ├── migrations
│   ├── models.py
│   ├── tests.py
│   ├── urls.py
│   └── views.py
├── static
│   └── css   
│       └── style.css
└── templates
    ├── base.html
    ├── registration
    │   ├── base.html
    │   ├── logged_out.html
    │   ├── login.html
    │   └── signup.html
    └── app
        └── index.html

The settings directory, the URLconf in django.contrib.auth specified in it, and the URlconf in the application directory are shown below.

Configuration file URLconf

config/urls.py


from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('app.urls')),
    path('accounts/', include('django.contrib.auth.urls')),  #Urls provided by Django in advance.To py
    path('accounts/', include('accounts.urls')),  #Urls I created.To py
]

django/contrib/auth/urls.py


from django.contrib.auth import views
from django.urls import path

urlpatterns = [
    path('login/', views.LoginView.as_view(), name='login'),
    path('logout/', views.LogoutView.as_view(), name='logout'),

    path('password_change/', views.PasswordChangeView.as_view(), name='password_change'),
    path('password_change/done/', views.PasswordChangeDoneView.as_view(), name='password_change_done'),

    path('password_reset/', views.PasswordResetView.as_view(), name='password_reset'),
    path('password_reset/done/', views.PasswordResetDoneView.as_view(), name='password_reset_done'),
    path('reset/<uidb64>/<token>/', views.PasswordResetConfirmView.as_view(), name='password_reset_confirm'),
    path('reset/done/', views.PasswordResetCompleteView.as_view(), name='password_reset_complete'),
]

Application URLconf

app/urls.py


from django.urls import path
from . import views

app_name = 'app'
urlpatterns = [
    path('', views.IndexView.as_view(), name='index'),
]

accounts/urls.py


from django.urls import path
from . import views

app_name = 'accounts'
urlpatterns = [
    path('signup/', views.SignUpView.as_view(), name='signup'),
]

Main subject

New registration completed → Enter on the login screen → Login completed

First, check the state before mounting.

accounts/views.py


from django.urls import reverse_lazy
from django.views import generic

from .forms import UserCreateForm


class SignUpView(generic.CreateView):
    form_class = UserCreateForm
    template_name = 'registration/signup.html'
    success_url = reverse_lazy('login')

New registration completed → Login completed

After the new registration is completed, you only need to make a small change to acccouts / views.py to complete the login without going through the login screen.

accounts/views.py


from django.urls import reverse_lazy
from django.views import generic
from django.contrib.auth import login, authenticate    #add to

from .forms import UserCreateForm


class SignUpView(generic.CreateView):
    form_class = UserCreateForm
    success_url = reverse_lazy('app:index')   #Change
    template_name = 'registration/signup.html'

    #Added below
    def form_valid(self, form):
        response = super().form_valid(form)
        username = form.cleaned_data.get('username')
        password = form.cleaned_data.get('password1')
        user = authenticate(username=username, password=password)
        login(self.request, user)
        return response

There are two tasks to do: specifying success_url and overriding the form_valid method.

Recommended Posts

[Django] I want to log in automatically after new registration
I want to pin Datetime.now in Django tests
I can't log in to the admin page with Django3
I tried to log in to twitter automatically with selenium (RPA, scraping)
I want to print in a comprehension
I want to embed Matplotlib in PySimpleGUI
I want to use the Django Debug Toolbar in my Ajax application
I want to do Dunnett's test in Python
I want to create a window in Python
I implemented Google's Speech to text in Django
I want to log file I / O on Linux
I want to display the progress in Python!
I want to upload a Django app to heroku
[Django memo] I want to set the login user information in the form in advance
I want to write in Python! (1) Code format check
I want to easily implement a timeout in python
I want to transition with a button in flask
I want to use self in Backpropagation (tf.custom_gradient) (tensorflow)
I want to write in Python! (2) Let's write a test
Even in JavaScript, I want to see Python `range ()`!
I want to randomly sample a file in Python
TemplateView patterns you'll want to learn first in Django
I want to work with a robot in python.
I want to send a business start email automatically
I want to use the R dataset in python
I want to do something in Python when I finish
I want to manipulate strings in Kotlin like Python!
I want to do Wake On LAN fully automatically
I want to get an error message in Japanese with django Password Change Form
I want to easily delete columns containing NA in R
I want to do something like sort uniq in Python
I want to make a blog editor with django admin
I want to automatically generate a modern metal band name
How to log in automatically like 1Password from the CLI
I want to solve Sudoku (Sudoku)
I want to automatically attend online classes with Python + Selenium!
I want to make the Dictionary type in the List unique
[Introduction to Pytorch] I want to generate sentences in news articles
I want to count unique values in arrays and tuples
I want to align the significant figures in the Numpy array
I want to be able to run Python in VS Code
I want to make input () a nice complement in python
How to log in to AtCoder with Python and submit automatically
I didn't want to write the AWS key in the program
I want to record the execution time and keep a log.
I want to automatically find high-quality parts from the videos I shot
Automatically acquire the operation log in the terminal when logging in to Linux
[Linux] I want to know the date when the user logged in
I want to solve APG4b with Python (only 4.01 and 4.04 in Chapter 4)
MacBookPro Setup After all I want to do a clean installation
I want to run Rails with rails s even in vagrant environment
LINEbot development, I want to check the operation in the local environment
[Python / AWS Lambda layers] I want to reuse only module in AWS Lambda Layers
I want to automatically answer Google Form at 5 o'clock every morning
Try to log in to Netflix automatically using python on your PC
I want to create a pipfile and reflect it in docker
I want to make the second line the column name in pandas
I want to pass the G test in one month Day 1
I want to know the population of each country in the world.
Errors related to memcached in django
I want to understand systemd roughly