Django | Codecademy | Accounts and Authentication
21658 ワード
Admin Account
In order to access the Admin interface, we must create a superuser
python3 manage.py createsuperuser
/admin
route and log in with the credentials we just used to create our superuser Registering Tables in Admin
In order to interact with a database table through the admin interface, we first need to register the model.
1. Registering and configuring a model is done by adding the models into the app’s admin.py
file# myapp_root/book_catalog/admin.py
from .models import Book
admin.site.register(Book)
# myapp_root/book_catalog/admin.py
from .models import Book
admin.site.register(Book)
register()
method to register our models admin.site.register(Book)
User Objects
from django.contrib.auth.models import User
.create_user()
user = User.objects.create_user(username="myusername", email="[email protected]", password="mypassword")
.save()
method in order to save the user object back to the database if we make any further changes. user = User.objects.create_user(username="myusername", email="[email protected]", password="mypassword")
**終了shellCtrl+D
orexit()
Authenticating Users
ViewFunctionにユーザ認証ロジックを追加し、authenticate()
functionを実行します.
user = authenticate(request, username=username, password=password)
User object
が返されます.django.shortcuts
redirect()
では、name of a viewを入力することで、ユーザーを特定のビューにリダイレクトできます.PermissionDenied exception
,None
が返されます.request.POST
フォーマットで入力されたデータを解析from django.contrib.auth import authenticate
def login_view(request):
# Both username and password are captured from the submitted log in form
username = request.POST["username"]
password = request.POST["password"]
# Both username and password are passed into the authenticate() method to verify the user
user = authenticate(request, username=username, password=password)
# If the user is valid, then a user object is returned.
if user is not None:
# Log in user and redirect them
return redirect("home.html")
else:
return HttpResponse("Invalid credentials!")
Log In
user objectが作成されている場合は、その認証情報を使用してサイトにログインできます.
Djangoが提供するlogin()
関数を使用すればいいです.# views.py
From django.contrib.auth import login
def login_view(request):
# ... Other code
login(request, user)
# views.py
From django.contrib.auth import login
def login_view(request):
# ... Other code
login(request, user)
django.contrib.auth
import login()
関数は、2つのrequest
、user
を受け入れます.ユーザーのログインとログアウトの時間.
from django.contrib.auth import authenticate, login
from django.shortcuts import redirect
def login_view(request):
username = request.POST["username"]
password = request.POST["password"]
user = authenticate(request, username=username, password=password)
# Check if a user is verified and authenticated
if user is not None:
# Use the returned user object in login()
login(request, user)
# Redirect to home page after logging in
return redirect("home.html")
else:
render(request, "registration/login.html", context)
現在、私たちのif
statementでは、(
request
+作成したuser
objectを含む)セッションは
login()
で作成できます.# Other login_view code...
if user is not None:
login(request, user)
return redirect("dashboard.html")
else:
render(request, "registration/login.html", context)
Login Mixin and Decorator
Login Mixin
mixins
= a type of class that is used to “mix in” extra properties and methods into another class. LoginRequiredMixin
from django mixins# views.py
from django.contrib.auth.mixins import LoginRequiredMixin
Mixins can be passed as argumentWe want to add login mixin before view (
left: mixin, right: view
)# views.py
class SomeView(LoginRequiredMixin, ListView):
model = ModelExample
Decorators
# views.py
from django.contrib.auth.decorators import login_required
@login_required
def profile(request):
return render(request, "app/profile.html", name="profile")
Decoratorを使用すると、ログインしていないユーザーを拒否できます.Log-out
logout()
function takes in a request
and returns None
: # views.py
from django.contrib.auth import logout
def logout_view(request):
# ... Other logic
logout(request)
return redirect("home")
logout()
function we completely delete the session data that was associated with the logged in user. thelogout()
function doesn’t throw any errors if the user is not logged in. Once the logout function is called, we can then redirect the user to a different view page by using redirect()
. add a new path to logout our users in our app’s urls.py:
urlpatterns = [
path("/logout", logout, name="logout")
]
このルートディレクトリは、セッションの終了後にログアウトされます.Login Template <!-- registration/login.html -->
{% block title %}Login{% endblock %}
{% block content %}
<h2>Login</h2>
<form method="post">
{% csrf_token %}
<table>
{{ form.as_p }}
<tr>
<td> </td>
<td><input type="submit" value="Submit"></td>
</tr>
</table>
</form>
{% endblock %}
Signup Template and View UserCreationForm
&CreateView
class-based viewの使用# views.py
from django.contrib.auth.forms import UserCreationForm
from django.urls import reverse_lazy
class SignUp(CreateView):
form_class = UserCreationForm
success_url = reverse_lazy("login")
template_name = "registration/signup.html"
Our SignUp
class is using a CreateView
class, in which we can specify what information to include.
<!-- registration/login.html -->
{% block title %}Login{% endblock %}
{% block content %}
<h2>Login</h2>
<form method="post">
{% csrf_token %}
<table>
{{ form.as_p }}
<tr>
<td> </td>
<td><input type="submit" value="Submit"></td>
</tr>
</table>
</form>
{% endblock %}
UserCreationForm
&CreateView
class-based viewの使用# views.py
from django.contrib.auth.forms import UserCreationForm
from django.urls import reverse_lazy
class SignUp(CreateView):
form_class = UserCreationForm
success_url = reverse_lazy("login")
template_name = "registration/signup.html"
Our SignUp
class is using a CreateView
class, in which we can specify what information to include.form_class
as a UserCreationForm
which will generate the necessary fields for us (username and password).UserCreationForm
was imported from django.contrib.auth.forms
success_url
attribute to assign a URL to redirect the signed up userreverse_lazy()
method to generate a full URL from a name. "login"
path since we still want a user to login. "registration/signup.html"
to template_name
so we can render that specific template. # urls.py
path("signup/", views.SignUp.as_view(), name="signup"),
Reference
この問題について(Django | Codecademy | Accounts and Authentication), 我々は、より多くの情報をここで見つけました https://velog.io/@celeste/Django-Codecademy-Accounts-and-Authenticationテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol