[PYTHON] Implementation of login function in Django

This is my memorandum. I did a lot of research for self-study, but since there were many explanations of version 2 etc., it was complicated, so I will summarize it to some extent. I am writing it in the hope that it will be of benefit to those who have encountered similar problems. Please watch with warm eyes! (Please do not hesitate to make any corrections)

You can understand most things by doing a tutorial (appropriate) https://docs.djangoproject.com/ja/3.1/intro/tutorial01/


Usage environment
・ OS ... windows10 ・ Python ... 3.7.6 ・ Django ... 3.1.3

Environment construction You can install python locally, but considering package management etc., is it better to use anaconda? If you look around here, you will find a lot, so let's go through.

I'm sorry if there is an oversight. The package is probably

pip install django
pip install pillow

It should have been just ...! !!

Let's Start Project!!

This is also a tutorial around here ...

I will write mainly where I stumbled from here.

Implementation around login Django comes with an admin site by default. When creating your own blog site etc., it seems good to use this management screen. What I wanted to do was
  1. Anyone can create an account
  2. Create my page for each user

I wanted to implement the function, so I made my own login function. As a flow

    1. Creating an app that performs login processing with the start app command
  1. Define user information in Model (inherit AbstractUser)
  2. Create a View for login and logout with LoginView and LogoutView
  3. As for new registration, View does not exist, so you can use your own method.
  4. Associate Model and View in Form I proceeded with the above feeling.

2:

model.py


class User(AbstractUser):
    pass

And just inherited AbstractUser. For the time being, the official document says that you should make your own by overriding. You can add your favorite columns by editing here. [Refer to Abstract User] https://docs.djangoproject.com/en/3.1/topics/auth/customizing/

3: I was thinking of the following options as a method of implementing the login and logout functions.

view.py


from django.contrib.auth import authenticate, login

def my_view(request):
    username = request.POST['username']
    password = request.POST['password']
    user = authenticate(request, username=username, password=password)
    if user is not None:
        login(request, user)
        # Redirect to a success page.
        ...
    else:
        # Return an 'invalid login' error message.
        ...

as well as

Method using View Reference source: https://docs.djangoproject.com/ja/3.1/topics/auth/default/

Since the amount of code is reduced when using View, I implemented it here, but it seems that the method that is intuitively easy to understand is the method of processing within the former method. When using View, be sure to check the variables inside. The causes of useless code and errors are listed relatively. Speaking this time, Form is the default because it is used when giving a class name in html. I edit only template_name and inherit the rest as it is. Logout is implemented in the same way, so it is omitted.

4: The new registration screen stumbled the most. I will write from the conclusion.

view.py


def signup(request):
    if request.method == 'POST':
        form = UserCreateForm(request.POST)
        if form.is_valid():
            form.save()
        else:
            print(form.errors)
        return redirect('/login')
    return render(request, 'loginauth/create_user.html')

def redirect_view(request):
    response = redirect('/login')
    return response

forms.py


class UserCreateForm(UserCreationForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['username'].widget.attrs['class'] = 'form-control'
        self.fields['password1'].widget.attrs['class'] = 'form-control'
        self.fields['password2'].widget.attrs['class'] = 'form-control'
        self.fields['email'].widget.attrs['class'] = 'form-control'

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

It's like that. I will supplement it.

The most complicated part personally Views.py ``` form = UserCreateForm (request.POST)` `` was. To briefly summarize what you are doing There is a Form called UserCreationForm for creating a User, Set Model: User and fields on the form. Extract the contents of views.py that match fields from request.POST and check if password1 and 2 match with form.is_valid (). If they match, save as is.

It is a flow. Reference source: https://docs.djangoproject.com/ja/3.1/topics/auth/default/ https://docs.djangoproject.com/ja/3.1/topics/auth/default/#django.contrib.auth.forms.UserCreationForm If you read around here, you can see how to write it.

Conclusion You can usually solve it by reading Document. Then you need to make an effort to interpret it For that purpose, we have to understand the processing performed in the contents of the package etc.! !! !! !! By the way, I don't know at all yet, so I read the contents every time I have time. If you look at the variables of methods and classes when you get stuck, there are many hints, so it is recommended

Recommended Posts

Implementation of login function in Django
Implementation of quicksort in Python
Introduction and implementation of activation function
Easy implementation of credit card payment function with PAY.JP [Django]
Implementation of life game in Python
The meaning of ".object" in Django
Implementation of original sorting in Python
Like button implementation in Django + Ajax
Django blog on heroku: login implementation
Implementation of JWT authentication functionality in Django REST Framework using djoser
It's an implementation of ConnectionPool in redis.py
Difference in output of even-length window function
Hello world instead of localhost in Django
Asynchronous processing implementation in Django (Celery, Redis)
Implementation of custom user model authentication in Django REST Framework with djoser
Duality in function
[Unity (C #), Python] API communication study memo ③ Implementation of simplified login function
Forms in Django
The _authenticate_with_backend function was obsolete in django auth.autenticate
Draw a graph of a quadratic function in Python
Fix the argument of the function used in map
Display error message when login fails in Django
Gacha written in python-Addition of period setting function-
Pass login user information to view in Django
The story of viewing media files in Django
Implement JWT login functionality in Django REST framework
Explanation of edit distance and implementation in Python
Reconsideration of paging implementation by Relay style in GraphQL (version using Window function)
This is a sample of function application in dataframe.
Execute function in parallel
Maximum likelihood estimation implementation of topic model in python
RNN implementation in python
ValueObject implementation in Python
Django drop-down menu implementation
Generator function in JavaScript
Impressions of touching Django
About testing in the implementation of machine learning models
[Cinema 4D] function of check all object in scene
Implementation of Fibonacci sequence
Model changes in Django
DataNitro, implementation of function to read data from sheet
Overview of generalized linear models and implementation in Python
Variational Bayesian inference implementation of topic model in python
A reminder about the implementation of recommendations in Python
SVM implementation in python
Explanation of NoReverseMatch error in "python django super introduction"
Set function of NumPy
I participated in the translation activity of Django official documents
Django + MongoDB development environment maintenance (in the middle of writing)
[Reinforcement learning] Explanation and implementation of Ape-X in Keras (failure)
Have the equation graph of the linear function drawn in Python
Summary of stumbling blocks in Django for the first time
A memo of writing a basic function in Python using recursion
Make the function of drawing Japanese fonts in OpenCV general
Django Changed to save lots of data in one go
Explanation of CSV and implementation example in each programming language
Performance optimization in Django 3.xx
Quantum computer implementation of quantum walk 2
PHP var_dump in Django templates
Handle constants in Django templates
Implement login function with django-allauth