Django NoReverseMatch at /register - django

I'm attempting to enable users to register on my Django based website; however I am running into the following error:
NoReverseMatch at /register
Reverse for 'register' not found. 'register' is not a valid view function or pattern name.
I am struggling to see what needs to be changed below, I feel that I have tried tweaking everything to get it working, but nothing seems to. I am using a namespace "Flightfinder" for my application, not sure if this has something to do with it?
Full Error:
NoReverseMatch at /register
Reverse for 'register' not found. 'register' is not a valid view function or pattern name.
Request Method: GET
Request URL: http://127.0.0.1:8001/register
Django Version: 3.1.3
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'register' not found. 'register' is not a valid view function or pattern name.
Exception Location: /mnt/c/Users/tjmce/Desktop/Git/CS50w/Final Project/finalproject/.venv/lib/python3.8/site-packages/django/urls/resolvers.py, line 685, in _reverse_with_prefix
Python Executable: /mnt/c/Users/tjmce/Desktop/Git/CS50w/Final Project/finalproject/.venv/bin/python3
Python Version: 3.8.5
Python Path:
['/mnt/c/Users/tjmce/Desktop/Git/CS50w/Final Project/finalproject',
'/usr/lib/python38.zip',
'/usr/lib/python3.8',
'/usr/lib/python3.8/lib-dynload',
'/mnt/c/Users/tjmce/Desktop/Git/CS50w/Final '
'Project/finalproject/.venv/lib/python3.8/site-packages']
Server time: Wed, 11 Nov 2020 20:32:27 +0000
Layout Template:
{% load static %}
<!doctype html>
<html lang="en">
<head>
<!-- jQuery & jQuery UI -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<!-- Bootstrap (includes Popper) -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx" crossorigin="anonymous"></script>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Main CSS-->
<link rel="stylesheet" type="text/css" href="{% static 'flightfinder/styles.css' %}">
<!-- Main JS -->
<script src="{% static 'flightfinder/main.js' %}"></script>
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
<!-- Font Awesome Icons -->
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.0/css/all.css" integrity="sha384-lZN37f5QGtY3VHgisS14W3ExzMWZxybE1SJSEsQp9S+oqd12jhcu+A56Ebc1zFSJ" crossorigin="anonymous">
<title>{% block title %}Flight Finder{% endblock %}</title>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light">
<a class="navbar-brand" href="{% url 'Flightfinder:index' %}">
<img src="https://i.ibb.co/TRBkPBZ/Flight-Finder-removebg-preview.png" width="166" height="42" class="d-inline-block align-top" alt="">
</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNavAltMarkup">
<div class="navbar-nav">
<a class="nav-item nav-link active" href="{% url 'Flightfinder:index' %}">Flights <span class="sr-only">(current)</span></a>
<a class="nav-item nav-link" href="#">Hotels</a>
<a class="nav-item nav-link" href="#">Car Hire</a>
</div>
<div class="navbar-nav ml-auto">
{% if user.is_authenticated %}
<a class="nav-item nav-link" href="{% url 'Flightfinder:logout' %}">Log Out</a>
<a class="nav-item nav-link" href="#">Account</a>
{% else %}
<a class="nav-item nav-link" href="{% url 'Flightfinder:login' %}">Log In</a>
<a class="nav-item nav-link" href="{% url 'Flightfinder:register' %}">Register</a>
{% endif %}
</div>
</div>
</nav>
{% block body %}
{% endblock %}
</body>
</html>
Views.py:
def register(request):
if request.method == "POST":
username = request.POST["username"]
email = request.POST["email"]
# Ensure password matches confirmation
password = request.POST["password"]
confirmation = request.POST["confirmation"]
if password != confirmation:
return render(request, 'flightfinder/register.html', {
"message": "Passwords must match."
})
# Attempt to create new user
try:
user = User.objects.create_user(username, email, password)
user.save()
except IntegrityError:
return render(request, 'flightfinder/register.html', {
"message": "Username already taken."
})
login(request, user)
return HttpResponseRedirect(reverse("index"))
else:
return render(request, 'flightfinder/register.html')
Urls.py - Main:
urlpatterns = [
path('', include('flightfinder.urls', namespace='Flightfinder')),
path('admin/', admin.site.urls),
]
Urls.py - App:
app_name = 'flightfinder'
urlpatterns = [
path('', views.index, name='index'),
path("login", views.login_view, name="login"),
path("logout", views.logout_view, name="logout"),
path("register", views.register, name="register"),
path('origin_airport_search/', views.origin_airport_search, name='origin_airport_search')
]
Thank you in advance for having a look into this for me, very much appreciated!

Related

Django Breadcrumb error: Reverse for 'projectnotes_list' with no arguments not found

I am trying to use django-views-breadcrumbs to add breadcrumbs to a site. I can get it to work with some views but I am getting an error with a particular listview. When I attempt to visit this listview page I see the error.
The error appears to be related to a need for the correct context. So far I have not been able to figure this out.
The error:
NoReverseMatch at /projects/project/1/notes/
Reverse for 'projectnotes_list' with no arguments not found. 1 pattern(s) tried: ['projects/project/(?P<pk>[0-9]+)/notes/\\Z']
Request Method: GET
Request URL: http://co1.localhost:8000/projects/project/1/notes/
Django Version: 3.1.14
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'projectnotes_list' with no arguments not found. 1 pattern(s) tried: ['projects/project/(?P<pk>[0-9]+)/notes/\\Z']
Exception Location: /Users/user/.local/share/virtualenvs/osite-wGphEfbP/lib/python3.9/site-packages/django/urls/resolvers.py, line 689, in _reverse_with_prefix
Python Executable: /Users/user/.local/share/virtualenvs/osite-wGphEfbP/bin/python
Python Version: 3.9.6
Python Path:
['/Users/user/Desktop/otools',
'/Library/Frameworks/Python.framework/Versions/3.9/lib/python39.zip',
'/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9',
'/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/lib-dynload',
'/Users/user/.local/share/virtualenvs/osite-wGphEfbP/lib/python3.9/site-packages']
Server time: Sun, 20 Feb 2022 15:52:17 +0000
The list view:
class ProjectNotesList(ListBreadcrumbMixin,ListView):
model = ProjectNotes
template_name = 'company_accounts/project_notes.html'
comments = ProjectNotes.comments
def related_project(self, **kwargs):
project = get_object_or_404(Project, id=self.kwargs.get('pk'))
notes = ProjectNotes.objects.all
return notes
def get_context_data(self, **kwargs):
# Call the base implementation first to get a context
context = super().get_context_data(**kwargs)
context['project'] = get_object_or_404(Project, id=self.kwargs.get('pk'))
return context
commentscount = ProjectNotes.objects.annotate(num_comments=Count('comments'))
The urls.py
from django.urls import path, include
from .views import CompanyProjects, CompanyProjectsDetailView, TodoCreateView, ProjectNotesList, ProjectNotesCreateView, ProjectCreateView, ProjectNotesDetailView, CompanyCompletedProjects, CompanyPausedProjects, TodosList, ProjectTodosDetailView, ProjectDocumentsList, ProjectDocumentsCreateView, ProjectDocumentsDetailView
from . import views
app_name = 'company_project'
urlpatterns = [
path('', CompanyProjects.as_view(), name='project_list'),
path('completed_projects', CompanyCompletedProjects.as_view(), name='completed_projects'),
path('paused_projects', CompanyPausedProjects.as_view(), name='paused_projects'),
path('add_project/', ProjectCreateView.as_view(), name='add_project'),
path('project/<int:pk>/', CompanyProjectsDetailView.as_view(), name='project_detail'),
path('project/<int:pk>/todos/', TodosList.as_view(), name='project_todos'),
path('project/<int:project_pk>/todo/<int:pk>/', ProjectTodosDetailView.as_view(), name='project_todo_detail'),
path('project/<int:pk>/add_todo/', TodoCreateView.as_view(), name='add_todo'),
path('project/<int:pk>/add_project_note/', ProjectNotesCreateView.as_view(), name='add_project_note'),
path('project/<int:pk>/notes/', ProjectNotesList.as_view(), name='projectnotes_list'),
#path('note/<int:pk>/add_project_note_comment/', ProjectNotesCommentCreateView.as_view(),
# name='add_project_note_comment'),
path('project/<int:project_pk>/note/<int:pk>/', ProjectNotesDetailView.as_view(), name='project_note_detail'),
path('project/<int:pk>/documents/', ProjectDocumentsList.as_view(), name='project_documents'),
path('project/<int:pk>/add_project_document/', ProjectDocumentsCreateView.as_view(), name='add_project_document'),
path('project/<int:project_pk>/document/<int:pk>/', ProjectDocumentsDetailView.as_view(), name='project_document_detail'),
]
The base and page templates:
base
<!DOCTYPE html>
{% load static %}
{% load view_breadcrumbs %}
<html>
<head>
<meta charset="utf-8">
<title>{% block title %}Site{% endblock title %}</title>
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link type="text/x-scss" href="{% static 'bootstrap/scss/bootstrap.scss' %}" rel="stylesheet" media="screen">
<!-- Custom CSS -->
<link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}"/>
<link rel="shortcut icon" type="image/png" href="{% static 'core_images/OH_favicon.png' %}"/>
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-VJRXH7YFXZ"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-VJRXH7YFXZ');
</script>
</head>
<body>
<wrapper class="d-flex flex-column">
{% include 'nav.html' %}
<main class="flex-fill">
<div class="row">
<div class="col-12">
<br />
{% block breadcrumbs %}
{% render_breadcrumbs 'view_breadcrumbs/bootstrap4.html' %}
{% endblock breadcrumbs %}
{% block messages %}{% endblock messages %}
</div>
</div>
{% block content %}
<h1>Hello</h1>
{% endblock content %}
</main>
{% include 'footer.html' %}
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script
src="https://code.jquery.com/jquery-3.6.0.min.js"
integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
</wrapper>
</body>
</html>
page
<!-- templates/company_accounts/project_notes.html -->
{% extends 'base.html' %}
{% block content %}
<div class="section-container container">
<div class="general-section-header">
<div class="header-add-new">
<a class="btn btn-success" href="{% url 'company_project:add_project_note' project.pk %}" role="button">Add Note</a>
</div>
<h1>Notes for {{ project }}</h1>
</div>
{% if project.notes.all %}
{% for note in project.notes.all %}
<div class ="projectnotes-entry">
<div class="col-sm-8">
<div class="row-sm-6">
<div class="card mb-2">
<div class="card-body">
<div class="card-title">{{ note.title }}</div>
<div class="card-text">{{ note.body | safe | truncatewords:"20"|linebreaks }}
<div>{{ note.comments.all.count }} comments</div>
read more</div>
</div>
</div>
</div>
</div>
</div>
{% endfor %}
{% else %}
<p>No notes have been have been added yet.</p>
{% endif %}
</div>
{% endblock content %}
There is a demo included with the breadcrumb app the provides some insight. However I have not been able to figure out how to add necessaryt context using code from the demo.
The demo code:
class TestListsView(ListBreadcrumbMixin, ListView):
model = TestModel
template_name = "demo/test-list.html"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
view_paths = []
for instance in self.object_list:
view_paths.append(
(
instance.name,
detail_instance_view_url(instance),
),
)
context["view_paths"] = view_paths
return context

How to generate a url that redirects to a specific view of another application

I'm working on a website, where I want to show all my django project.
So, I have a main app, where i'm generating template for all my projects
my home template when we access to the website:
<!doctype html>
{% load static %}
<html lang="fr">
<head>
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" type="text/css" href="{% static 'home/css/style.css' %}">
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Nerko+One&family=Roboto&display=swap&family=Open+Sans&display=swap" rel="stylesheet">
<meta name="viewport" content="width=device-width"/>
</head>
<body>
<header>
<h1></h1>
<span class="separator"></span>
<h2></h2>
<img src="{% static '/home/pictures/logo.png' %}" alt="logo" title="Ceci est mon logo" id="logo">
</header>
<nav>
<ul>
<li>Accueil</li>
<li>Projets</li>
<li>Contact</li>
</ul>
</nav>
<div class="contener">
<section>
<h3>Projets</h3>
<!-- conteneur -->
<div id="projects">
{% for projet in projets %}
<div class="project">
<a href="{% url 'projet-detail' projet.nom_lien %}">
<div class="picture">
<img src="{% static '' %}{{ projet.lien_image_presentation }}" alt="Présentation {{ projet.nom }}">
</div>
<span>{{ projet.nom }}</span>
<span class="date-project">{{ projet.date }}</span>
</a>
</div>
{% endfor %}
</div>
</section>
<section>
<h3>Contact</h3>
<div id="contact">
<p>Si vous désirez me contacter, n'hésitez pas à m'écrire à l'adresse <b>aymerick.cotche#hotmail.fr</b></p>
</div>
</section>
</div>
<footer>
<span>2020 © - Aymerick Cotche</span>
</footer>
</body>
</html>
template to see my project description :
{% load static %}
<html lang="fr">
<head>
<meta charset="UTF-8">
<title>{{ projet.nom }} | {{ projet.auteur }}</title>
<link rel="stylesheet" type="text/css" href="{% static 'home/css/style.css' %}">
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Nerko+One&family=Roboto&display=swap&family=Open+Sans&display=swap" rel="stylesheet">
<meta name="viewport" content="width=device-width"/>
</head>
<body>
<header>
<h1></h1>
<span class="separator"></span>
<h2>{{ projet.nom }}</h2>
</header>
<nav>
<ul>
<li>Accueil</li>
<li>Projets</li>
<li>Contact</li>
</ul>
</nav>
<div class="contener">
<section>
<h3>Introduction</h3>
<p> {{ projet.description }} </p>
</section>
<section id="production_project">
<h3>Production</h3>
<img src="{% static '' %}{{ projet.lien_image_production }}" alt="mon premier projet">
voir le projet
</section>
</div>
</body>
</html>
my urls file for this app:
from django.urls import path
from home import views
urlpatterns = [
path('', views.home),
path('<str:nom_lien>/', views.projet_detail, name='projet-detail'),
]
My views file for this app :
from django.shortcuts import render, redirect
from home.models import Projet
def home(request):
projets = Projet.objects.all().order_by('numero')
return render(request, 'home/index.html', {'projets': projets})
def projet_detail(request, nom_lien):
projet = Projet.objects.get(nom_lien=nom_lien)
context = {
'projet': projet
}
return render(request, 'home/projets_base.html', context)
That I want to do it's to have a link in my project description template, to go to the project, and use the project. The project it's another django app in the same project. and this link should be like "/nom-lien/voirprojet/"
For example in my app "pizza mama" I have this url and views file:
from django.urls import path
from . import views
app_name = "main"
urlpatterns = [
path('pizzamama/voirprojet/', views.index, name="index"),
]
The link have to use the Projet.nom_lien field in my database and redirect to the the project page.
Could someone help me please, I'm stuck and can't make it works.
you want to store the link in the database
define in models.py a class Project
class Project(models.Model):
link_to_app = models.CharField(max_length=50)
register it in the admin.py
in the admin panel enter the what you want Links
then you can access it like this in urls.py
from .models import Link
link = Projects.objects.get(pk=1)
my_link = link.link_to_app
then pass my_link to the url path
urlpatterns += [
path(my_link, views.index, name='index')),
]

Django NoReverseMatch - Amadeus API

I'm attempting to use an API as part of a project I'm working on and am having some difficulty currently:
API
https://developers.amadeus.com/self-service/category/air/api-doc/airport-and-city-search
API - Python SDK
https://github.com/amadeus4dev/amadeus-python
Django API Guide
https://developers.amadeus.com/blog/django-jquery-ajax-airport-search-autocomplete
I have followed the instructions from the above guide; however, I am receiving the following error when trying to render the index page which contains the code:
Reverse for 'origin_airport_search' not found. 'origin_airport_search' is not a valid view function or pattern name.
Index Template:
{% extends "flightfinder/layout.html" %}
{% block body %}
<div id="mainhomepagediv">
<div class="container-fluid px-0" id="mainhomepagediv">
<div class="row mx-0">
<div class="col-12 px-0">
<img src="https://i.ibb.co/rHYzcyc/Landscape2.jpg" class="img-fluid w-100">
</div>
</div>
</div>
<div>
<h1 id="homepageh1">Where are you flying to?</h1>
<div id="homepagebox">
<div>
<form id="homepageform" method="POST">
<div class="row">
<div class="col">
<label id="homepageformlabel">From</label>
<input type="text" class="form-control" placeholder="Origin city" id="inputOrigin">
</div>
<div class="col pb-3">
<label id="homepageformlabel">To</label>
<input type="text" class="form-control" placeholder="Destination city">
</div>
</div>
<div class="row">
<div class="col">
<label id="homepageformlabel">Depart</label>
<input type="date" class="form-control" placeholder="Origin city">
</div>
<div class="col">
<label id="homepageformlabel">Return</label>
<input type="date" class="form-control" placeholder="Destination city">
</div>
<div class="col-6">
<label id="homepageformlabel">Class</label>
<select id="inputState" class="form-control">
<option selected>Economy</option>
<option>Business</option>
<option>First</option>
</select>
</div>
</div>
<div class="row">
<div class="col">
</div>
<div class="col-3 pt-3">
<button class="btn float-right" id="homepageformbutton" type="submit">Search flights</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
<script>
// Amadeus origin airport search
$(document).ready(function () {
$("#inputOrigin").autocomplete({
source: "{% url 'origin_airport_search' %}",
minLength: 1,
delay: 200,
});
});
</script>
{% endblock %}
Layout Template:
{% load static %}
<!doctype html>
<html lang="en">
<head>
<!-- jQuery & jQuery UI -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<!-- Bootstrap (includes Popper) -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx" crossorigin="anonymous"></script>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Main CSS-->
<link rel="stylesheet" type="text/css" href="{% static 'flightfinder/styles.css' %}">
<!-- Main JS -->
<script src="{% static 'flightfinder/main.js' %}"></script>
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
<!-- Font Awesome Icons -->
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.0/css/all.css" integrity="sha384-lZN37f5QGtY3VHgisS14W3ExzMWZxybE1SJSEsQp9S+oqd12jhcu+A56Ebc1zFSJ" crossorigin="anonymous">
<title>{% block title %}Flight Finder{% endblock %}</title>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light">
<a class="navbar-brand" href="{% url 'flightfinder:index' %}">
<img src="https://i.ibb.co/TRBkPBZ/Flight-Finder-removebg-preview.png" width="166" height="42" class="d-inline-block align-top" alt="">
</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNavAltMarkup">
<div class="navbar-nav">
<a class="nav-item nav-link active" href="{% url 'flightfinder:index' %}">Flights <span class="sr-only">(current)</span></a>
<a class="nav-item nav-link" href="#">Hotels</a>
<a class="nav-item nav-link" href="#">Car Hire</a>
</div>
</div>
</nav>
{% block body %}
{% endblock %}
</body>
</html>
Main - urls.py:
"""finalproject URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
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 include, path
urlpatterns = [
path('', include('flightfinder.urls', namespace='Flightfinder')),
path('admin/', admin.site.urls),
]
App - urls.py:
from django.urls import path
from . import views
app_name = 'flightfinder'
urlpatterns = [
path('', views.index, name='index'),
path('origin_airport_search/', views.origin_airport_search, name='origin_airport_search')
]
views.py:
import json
from django.shortcuts import render
from django.http import HttpResponse
from django.contrib import messages
from amadeus import Client, ResponseError, Location
from .models import Airport, Flight, Passenger
amadeus = Client(client_id='removed',
client_secret='removed',
log_level='debug')
# Create your views here.
def index(request):
return render(request, 'flightfinder/index.html')
def origin_airport_search(request):
if request.is_ajax():
try:
data = amadeus.reference_data.locations.get(keyword=request.GET.get('term', None), subType=Location.ANY).data
except ResponseError as error:
messages.add_message(request, messages.ERROR, error)
return HttpResponse(get_city_airport_list(data), 'application/json')
def get_city_airport_list(data):
result = []
for i, val in enumerate(data):
result.append(data[i]['iataCode']+', '+data[i]['name'])
result = list(dict.fromkeys(result))
return json.dumps(result)
I have had a look through some similar stack queries, but none of them have helped thus far. Would be grateful if somebody had any ideas to try here?
Thank you!
You have set a namespace "Flightfinders" in your include. This means you have to use this namespace to call your URL:
source: "{% url 'Flightfinder:origin_airport_search' %}",

I am trying to use static files like css and images in my django project but statics files are not displayed in my template page

I want a image to be displayed in my navbar at the top left corner but its not visible and my css styling is also not styling my pages....in short my static files are not displayed in my project.
i think i have mentioned all the neccesary things if anything is missing please mention.
my settings.py----
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
STATIC_FILES = os.path.join(BASE_DIR,'static','static_files')
STATIC_ROOT = os.path.join(BASE_DIR,'static','static_root')
urls.py---
from Devishi import settings
from django.conf.urls.static import static
urlpatterns = [
path('',views.home,name='home'),
path('product/',views.products,name ='product'),
path('customer/',views.customer,name ='customer'),
]
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
main.html---
{% load static %}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>{% block title %}DASHBORD||{% endblock %}</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<link rel="stylesheet" href="{% static '/css/my.css' %}">
</head>
<body>
{% include 'app/navbar.html' %}
{% block content %}
{% endblock %}
<hr/>
<p>Our Footer</p>
</body>
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
</html>
navbar.html---
{% load static %}
<style media="screen">
.hello-msg{
font-size:18px;
color:#fff;
margin-right:20px;
}
</style>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<img src="{% static "img/logo.png" %}" alt="image">
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav">
<li class="nav-item active">
<a class="nav-link" href="#">Dashboard</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{% url 'product' %}">Products</a>
</li>
</ul>
</div>
</nav>

NoReverseMatch at /fileupload/ :Reverse for 'view' not found. 'view' is not a valid view function or pattern name

I'm trying to create a file upload page. I get this error just after successfully logging in. I don't what I'm missing looked over StackOverflow. There are many posts just like this but I'm not getting what to do in my code. Any help will be appreciated
Error during template rendering
In template /Users/mac/mrpash/csimplifypd/pd/templates/base.html, error at line 16
Exception Type: NoReverseMatch at /fileupload/
Exception Value: Reverse for 'view' not found. 'view' is not a valid view function or pattern name.
Here is my Urls.py
from django.urls import path
from django.conf import settings
from pd.views import FileUpload, Index, GetText
urlpatterns = [
path('', Index.index, name='login'),
path('fileupload/', FileUpload.fileup, name='fileupload'),
path('detected/', GetText.fileget, name='detected'),
]
also i divided my views into three different files.
they are
FileUpload.py
from pd.forms.FileUploadForm import DocumentForm
from django.shortcuts import render, redirect
from django.conf import settings
from django.core.files.storage import FileSystemStorage
def fileup(request):
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect("fileupload")
else:
form = DocumentForm()
return render(request, 'pd/FileUpload.html', {'form': form})
GetText.py
from django.shortcuts import render
from pd.models.ImageUpload import Img
# Create your views here.
def fileget(request):
if request.method == 'GET':
imgs = Img.objects.all()
return render(request, "pd/DetectedText.html", {'imgs': imgs})
Index.py
from django.shortcuts import render
from pd.models.UserForm import User
from pd.forms.UserForm import UserForm
from django.shortcuts import render, redirect
def index(request):
if request.method == 'POST':
username = request.POST.get('email')
password = request.POST.get('password')
u = User(username=username, password=password)
u.save()
return render(request, 'pd/login.html')
else:
return render(request, 'pd/login.html')
return render(request, 'pd/login.html')
This is my base.html
{% load static %}
<!DOCTYPE html>
<html>
<!--sudo lsof -t -i tcp:8000 | xargs kill -9-->
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css">
<link rel="stylesheet" type="text/css" href="{% static 'pd/css/login.css' %}">
<script src="{% static 'pd/js/login.js' %}"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS"
crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut"
crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k"
crossorigin="anonymous"></script>
<link rel="stylesheet" type="text/css" href="{% static 'pd/css/text.css' %}">
<script src="{% static 'pd/js/jscript.js' %}"></script>
<title>Login</title>
</head>
<body>
<!-- Header Starts-->
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="https://www.panasonic.com/in/"><img src="{% static 'textdetect/images/logo.png' %}"></a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarTogglerDemo02"
aria-controls="navbarTogglerDemo02" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarTogglerDemo02">
<ul class="navbar-nav mr-auto mt-2 mt-lg-0 pl-3 company">
<li class="nav-item active">
<a class="nav-link" href="#">DIGI QUOTE PRO</a>
</li>
</ul>
<div class="d-inline pl-3">
<ul class="navbar-nav mr-auto mt-2 mt-lg-0">
<li class="nav-item">
<a class="nav-link" href="#"><i class="fa fa-user-plus" aria-hidden="true"></i> Sign Up</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="#"><i class="fa fa-sign-in" aria-hidden="true"></i> Log In</a>
</li>
</ul>
</div>
</div>
</nav>
<!-- Header Ends-->
{% block content %}
{% endblock %}
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<script type="text/javascript" src="{% static 'pd/js/login.js' %}"></script>
</body>
</html>