# LoginView is already pre-created by Djangofromdjango.contrib.auth.viewsimportLoginView# Add a url to reach that viewpath('login/', LoginView.as_view(), name='login')
# By default the LoginView will try to open a template name 'registration/login.html' and send a login form with it.# Create a template under registration/login.html
{%extends"base.html"%}
{%blockcontent%}
<formmethod="post">
{%csrf_token%}
{{ form }}
<buttontype="submit">Login</button></form>
{%endblockcontent%}
# When user click the Login button, the LoginView will try to authenticate the user with the form username ans password. # If successful il will then login the user and redirect to LOGIN_REDIRECT_URL specified in your settings.py
Authentification: LogoutView
# LogoutView is already pre-created by Djangofromdjango.contrib.auth.viewsimportLogoutView# Add a url to reach that viewpath('logout/', LoginView.as_view(), name='logout')
# Include a link in a template<a>href="{% url 'logout' %}">Logout</a># After link is execute, the user will be logout and redirect to LOGOUT_REDIRECT_URL specified in your settings.py
Authentification: SignupView
# Create a SignupView (that view is not created by default)# import sinupview form pre-created by Djangofromdjango.contrib.auth.formsimportUserCreationFormfromdjango.views.genericimportCreateViewclassSignupView(CreateView):
template_name='registration/signup.html'form_class=UserCreationFormdefget_success_url(self):
returnreverse("login")
# Create template: registration/signup.html
{%extends"base.html"%}
{%blockcontent%}
<formmethod="post">
{%csrf_token%}
{{ form }}
<buttontype="submit">Signup</button></form>
{%endblockcontent%}
# Add a url to reach that viewfromposts.viewsimportSignupViewpath('signup/', SignupView.as_view(), name='signup')
# Optional: Customize the UserCreationForm# (forms.py)fromdjango.contrib.authimportget_user_modelfromdjango.contrib.auth.formsimportUserCreationFormUser=get_user_model()
classCustomUserCreationForm(UserCreattionForm):
classMeta:
model=Userfields= ['username']
fields_classes= {'username': UsernameField}
Optional pre-created authentification routes
# urls.pyurlpatterns+=path('', include('django.contrib.auth.urls'))
# /login, /lougout, /signup, etc.
Authorization: LoginRequiredMixin and login_required
fromdjango.contrib.auth.mixinsimportLoginRequiredMixin# Restrict views to auth user only (views.py)classPostsCreateView(LoginRequiredMixin, generic.CreateView):
...
...
fromdjango.contrib.auth.decoratorsimportlogin_required@login_required(login_url='/login')defsearch_page(request):
...
...