This article is a study memo for beginners who are also aiming to break away from Django beginners. There is a possibility of mistakes in word selection and interpretation.
--What is the User model? --How to make user --Implementation of login / logout
By default, Django includes a database for user management, which allows you to authenticate and manage users without hassle.
The User model has the following inheritance relationship and has the field names shown below.
You can also access the data like any other model object.
from django.contrib.auth.model import User
#By the way, the get method returns an error if the value cannot be obtained.
User.objects.get(username='admin')
User.objects.get(pk=1)
#By the way, the all method returns a queryset object
#Can be used like a list
User.objects.all()
--Make on the console
(virtualenv)~~~~~$python manage.py createsuperuser
Create a superuser with all privileges to access the Admin site.
--Make on admin site After running server, go to the Admin site and click Add
--Create in views.py
from django.contrib.auth.models import User
User.objects.create_user(username,email,password)
#If you want to jump to the page you logged in to immediately after registering as a user
#user = User.objects.create_user(username,email,password)
#Is convenient
from django.contrib.auth import authenticate, login, logout
def loginfunc(request):
#If it matches the User model, it returns an object, otherwise it returns none, so as follows
#Use if statement
#Immediately after registering User
#user = User.objects.create_user(username,email,password)Can be substituted with
user = authenticate(request, username=username, password=password)
if user is not None:
#Login
login(request, user)
return redirect('userpage')
else:
return redirect('signup')
def logoutfunc(request):
#Log out
logout(request)
return redirect('signup')
Recommended Posts