I am working on the login/logout functionality of a basic Django website. (CS50's Pinocchio's Pizza). The logout path is being injected into the URL & I am unsure as to why. My navbar links to the home page, yet when I click on it it redirects me to the logout page. Any other link I click, that link's path is added to the URL but attached to the logout path. For example, clicking on the login button of my site, whose path is login_default
, the url becomes:
http://127.0.0.1:8000/logoutlogin_default
Trying to click the link in the navbar that should link to the index
page gets me:
http://127.0.0.1:8000/logout
The folder "orders" is an app which "pizza" is made aware of. All html pages are inside orders/templates/orders
.
This is orders/urls.py
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name = "index"),
path("register_default", views.register_default, name = "register_default"),
path("register_setup", views.register_setup, name = "register"),
path("login_default", views.login_default, name = "login_default"),
path("login_setup", views.login_setup, name = "login"),
path("logout", views.logout_view, name="logout"),
]
In pizza/urls.py
, the Orders app's URLs have been made known:
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path("", include("orders.urls")),
path("register_default", include("orders.urls")),
path("register_setup", include("orders.urls")),
path("login_default", include("orders.urls")),
path("login_setup", include("orders.urls")),
path("logout", include("orders.urls")),
path("admin/", admin.site.urls),
]
This is orders/views.py
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import User
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
# Create your views here.
def index(request):
# If user is not logged in
if not request.user.is_authenticated:
return render(request, "orders/index.html", {"message": None})
context = {
"user": request.user
}
return render(request, "orders/index.html", context)
def register_default(request):
return render(request, "orders/register.html")
def register_setup(request):
firstName = request.POST["userFirstName"]
lastName = request.POST["userLastName"]
email = request.POST["userEmail"]
pw = request.POST["userPW"]
user = User.objects.create_user(firstName, email, pw)
user.save()
return HttpResponseRedirect(reverse("index"))
def login_default(request):
return render(request, "orders/login.html")
def login_setup(request):
username = request.POST["loginName"]
password = request.POST["loginPW"]
user = authenticate(username=username, password=password)
if user is not None:
login(request, user)
return HttpResponseRedirect(reverse("index"))
else:
return render(request, "orders/login.html", {"message": "Invalid Credentials"})
def logout_view(request):
logout(request)
return render(request, "orders/login.html", {"message": "Logged Out"})
This is base.html
, which all other templates are based off of.
<!DOCTYPE html>
<html lang="en">
<head>
{% block head %}{% endblock %}
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<title>{% block title %}{% endblock %}</title>
</head>
<body>
<nav class="navbar navbar-expand-md bg-light">
<a href="{% url 'index' %}" class="navbar-brand">Pinocchio's Pizza</a>
<ul class="navbar-nav">
{% if message %}
<li class="nav-item">
<a href="{% url 'logout' %}" class="nav-link">Log Out</a>
</li>
{% else %}
<li class="nav-item">
<a href="{% url 'login_default' %}" class="nav-link">Log In</a>
</li>
<li class="nav-item">
<a href="{% url 'register_default' %}" class="nav-link">Sign Up</a>
</li>
{% endif %}
</ul>
</nav>
{% block body %}{% endblock %}
</body>
</html>
This is login.html
{% extends "orders/base.html" %}
{% block title %}Log In{% endblock %}
{% block body %}
{% if message %}
<h1 class="text-danger">{{ message }}</h1>
{% endif %}
<div class="container-fluid">
<div class="row">
<div class="col-md-6 mx-auto mt-4">
<form action="{% url 'login' %}" method="POST">
{% csrf_token %}
<div class="form-group">
<label for="loginName">First Name</label>
<input type="text" name="loginName" id="loginName" class="form-control">
</div>
<div class="form-group">
<label for="loginPW">Password</label>
<input type="password" class="form-control" name="loginPW" id="loginPW">
</div>
<button class="btn btn-success" type="submit">Log In</button>
</form>
</div>
</div>
</div>
{% endblock %}
This is pizza/settings.py
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'i0&iq&e9u9h6(4_7%pt2s9)f=c$kso=k$c$w@fi9215s=1q0^d'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'orders.apps.OrdersConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'pizza.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'pizza.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.0/howto/static-files/
STATIC_URL = '/static/'
Try changing pizza/urls.py
to the following:
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path("", include("orders.urls")),
path("admin/", admin.site.urls),
]
the reason is the ""
path should automatically include all the urls in orders.urls
. Here is a link to the documentation: https://docs.djangoproject.com/en/2.2/topics/http/urls/#including-other-urlconfs
Another thing that I noticed that helps catch bugs is to include a /
at the end of urls so in your orders/urls.py
you can change it to the following.
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name = "index"),
path("register_default/", views.register_default, name = "register_default"),
path("register_setup/", views.register_setup, name = "register"),
path("login_default/", views.login_default, name = "login_default"),
path("login_setup/", views.login_setup, name = "login"),
path("logout/", views.logout_view, name="logout"),
]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.