This is the output page of the result of learning about Django on Udemy. The previous article is here .
This time, we will implement the login function in the diary application created last time.
settings.py Add LOGIN_URL to settings.py. This time, the login screen of the admin site will be used, so let's use admin: login. Add the following code to settings.py.
settings.py
LOGIN_URL = 'admin:login'
views.py This time, I would like to control the add / update / delete page so that login is required.
First edit views.py.
Import LoginRequiredMixin
.
Then, inherit LoginRequiredMixin
to the class you want to log in to.
This is all you need to do to implement the login function. The rest is HTML editing.
LoginRequiredMixin
before classes such as ListView. An error will occur.views.py
from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import render, redirect, get_object_or_404
from .forms import DayCreateForm
from .models import Day
from django.views import generic
from django.urls import reverse_lazy
class IndexView(generic.ListView):
model = Day
paginate_by = 3
class DayCreateView(LoginRequiredMixin, generic.CreateView):
model = Day
form_class = DayCreateForm
success_url = reverse_lazy('diary:index')
class DayUpdateView(LoginRequiredMixin, generic.UpdateView):
#It has almost the same contents as CreateView, but passes not only form but also Day object.
model = Day
form_class = DayCreateForm
success_url = reverse_lazy('diary:index')
class DayDeleteView(LoginRequiredMixin, generic.DeleteView):
model = Day
success_url = reverse_lazy('diary:index')
class DayDetailView(generic.DetailView):
model = Day
Next is HTML editing.
If you want to show something only after logging in, you can do it by enclosing it in the following if statement.
{% if user.is_superuser%} What you want to see after logging in {% endif%}
If you write as below, add and logout will be displayed after login, The login is displayed before login.
If you set target = "_ blank", login / logout will open in a separate tab.
base.html
<div class="container">
<nav class="nav">
<a class="nav-link active" href="{% url 'diary:index' %}">List</a>
{% if user.is_superuser %}
<a class="nav-link" href="{% url 'diary:add' %}">add to</a>
<a class="nav-link" href="{% url 'admin:logout' %}" target="_blank">Log out</a>
{% else %}
<a class="nav-link" href="{% url 'admin:login' %}" target="_blank">Login</a>
{% endif %}
</nav>
{% block content %}
{% endblock %}
</div>
Check the operation with py manage.py runserver. If you click the update / delete button, you will be taken to the login screen.
Recommended Posts