First, let's begin with making it possible to log in. Django has a built in view for this, so the only thing we need to handle is the url and the templates.
Open up userprofile/urls.py and make the following changes:
from django.contrib.auth import views as auth_views # 1. New
from django.urls import path
from . import views
urlpatterns = [
path('sign-up/', views.signup, name='signup'),
path('log-in/', auth_views.LoginView.as_view(template_name='userprofile/login.html'), name='login'), # 2. Change
]
1. First, we import all of the authentication views from Django. And we import them "as auth_views", so the names doesn't crash with ours.
2. Then, we append the path to the urlpatterns. This is a Class Based View, and the only thing we need to specify is where the template is located.
Django will handle all of the magic for us.
Create a new file called "login.html", and copy the contents from signup.html.
{% extends 'task/base.html' %}
{% block content %}
<div class="edit-tasks">
<h1>Log in</h1>
<form method="post" action=".">
{% csrf_token %}
{{ form.as_p }}
<button>Log in</button>
</form>
</div>
{% endblock %}
You can just rename the title and button.
We didn't see in the url file that there was supposed to be a variable called "form", but this is the default way for Django to handle this. So now you can try this out by going to "/log-in/" in your browser.
Last step of this part is to make some changes in the base.html file:
...
<nav class="navbar is-dark">
<div class="navbar-brand">
<a href="/" class="navbar-item is-size-4">Toodoo</a>
</div>
<div class="navbar-menu">
<div class="navbar-end">
{% if request.user.is_authenticated %}
<a class="navbar-item">Log out</a>
{% else %}
<a href="{% url 'signup' %}" class="navbar-item">Sign up</a>
<a href="{% url 'login' %}class="navbar-item">Log in</a>
{% endif %}
</div>
</div>
</nav>
...
So here we add a new menu inside the navigation bar. We use the if-tag from Django to check if the user is authenticated. If the user is not authenticated, we show the sign up and login links. But if the user is authenticated, we show a log out link (Will be implemented in the next part).
Table of contents
- 1. Introduction
- 2. Installation and setup
- 3. How things work
- 4. The first Django app
- 5. Your first view
- 6. Your first template
- 7. Testing our site
- 8. Extending templates
- 9. Your first model
- 10. The admin interface
- 11. Showing contents from the model
- 12. Another app (category)
- 13. Connecting two models
- 14. Show list of categories
- 15. Category detail page
- 16. Separate url files and why
- 17. Adding tasks in the front end
- 18. Editing tasks
- 19. Completing and deleting tasks
- 21. Prettying up the design a little bit
- 22. Make it possible to sign up
- 23. Logging in