1
0
Fork 0

Add basic login/logout

This commit is contained in:
Vili Sinervä 2024-11-24 16:11:22 +02:00
parent 28bbf51d21
commit 8f3b1f817a
No known key found for this signature in database
GPG key ID: DF8FEAF54EFAC996
5 changed files with 63 additions and 3 deletions

View file

@ -54,7 +54,7 @@ ROOT_URLCONF = 'notesapp.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'DIRS': [ 'notesapp/templates', ],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [

View file

@ -0,0 +1,10 @@
<!DOCTYPE html>
<html lang="en">
<body>
<form action="/accounts/logout/" method="POST">
{% csrf_token %}
<input type="submit" value="Log out">
</form>
<h1>Hello, logged in user {{user.username }}!</h1>
</body>
</html>

View file

@ -0,0 +1,16 @@
<!DOCTYPE html>
<html lang="en">
<body>
{% if login_failed %}
<p> Incorrect username or password! </p>
{% endif %}
<form action="/accounts/login/" method="POST">
{% csrf_token %}
<label for="username">Username:</label><br>
<input type="text" id="username" name="username"><br><br>
<label for="password">Password:</label><br>
<input type="password" id="password" name="password"><br><br>
<input type="submit" value="Log in">
</form>
</body>
</html>

View file

@ -13,9 +13,11 @@ Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from notesapp import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.index, name='index'),
path('accounts/login/', views.login_view, name='login'),
path('accounts/logout/', views.logout_view, name='logout'),
]

32
notesapp/views.py Normal file
View file

@ -0,0 +1,32 @@
from django.http import HttpResponse
from django.contrib.auth.decorators import login_required
from django.contrib.auth import authenticate, login, logout
from django.shortcuts import render, redirect
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth.models import User
from django.db import transaction
@login_required()
def index(request):
return render(request, 'index.html')
def login_view(request):
if request.method == 'GET':
return render(request, 'login.html')
elif request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(username=username, password=password)
if user is not None:
login(request, user)
return redirect("index")
else:
return render(request, 'login.html', { 'login_failed' : True })
return redirect("index")
def logout_view(request):
if request.method == 'POST':
logout(request)
return redirect("index")