Django - links are incorrectly resolved in menu - django

I am developing locally Django page and have some issues with highlighted menus.
when hover over "moje projekty" I see below link
127.0.0.1:8080/portfolio/, I click and page opens
when now I hover hover 2nd time, it is showing:
127.0.0.1:8080/portfolio/portfolio/, I click and page opens
when now I hover hover 3rd time,it is showing:
127.0.0.1:8080/portfolio/portfolio/portfolio/, I click and error is:
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8080/portfolio/portfolio/portfolio/
Using the URLconf defined in my_site.urls, Django tried these URL patterns, in this order:
admin/
[name='home']
about_me/ [name='aboutme']
portfolio/ [name='portfolio']
posts/<slug:the_slug>/ [name='post_detail']
summernote/
^media/(?P<path>.*)$
portfolio/ [name='home']
portfolio/ about_me/ [name='aboutme']
portfolio/ portfolio/ [name='portfolio']
portfolio/ posts/<slug:the_slug>/ [name='post_detail']
portfolio/ summernote/
portfolio/ ^media/(?P<path>.*)$
about_me/
The current path, portfolio/portfolio/portfolio/, didn’t match any of these.
base.html:
<!DOCTYPE html>
<html>
<head>
<title>Moja strona</title>
<link href="https://fonts.googleapis.com/css?family=Roboto:400,700" rel="stylesheet">
<meta name="google" content="notranslate" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"
crossorigin="anonymous" />
</head>
<body>
<style>
body {
font-family: "Roboto", sans-serif;
font-size: 17px;
background-color: #fdfdfd;
}
.shadow {
box-shadow: 0 4px 2px -2px rgba(0, 0, 0, 0.1);
}
.btn-danger {
color: #fff;
background-color: #f00000;
border-color: #dc281e;
}
.masthead {
background: #3398E1;
height: auto;
padding-bottom: 15px;
box-shadow: 0 16px 48px #E3E7EB;
padding-top: 10px;
}
img {
width: 00%;
height: auto;
object-fit: contain;
</style>
{% load static %}
<center> <img src="{% static 'blog/moj.png' %}" alt="My image"> </center>
<!-- Navigation -->
<nav class="navbar navbar-expand-sm navbar-light bg-light shadow" id="mainNav">
<div class="container-fluid">
<button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarResponsive"
aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarResponsive">
<ul class="navbar-nav ml-auto">
<li class="nav-item text-black">
<a class="nav-link text-black font-weight-bold" href="/">Blog</a>
</li>
<li class="nav-item text-black">
<a class="nav-link text-black font-weight-bold" href="portfolio/">Moje projekty</a>
</li>
<li class="nav-item text-black">
<a class="nav-link text-black font-weight-bold" href="about_me">Kontakt</a>
</li>
</ul>
</div>
</div>
</nav>
{% block content %}
<!-- Content Goes here -->
{% endblock content %}
<!-- Footer -->
</body>
</html>
urls.py project:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('blog.urls')),
path('portfolio/', include('blog.urls')),
path('about_me/', include('blog.urls')),
]
urls.py app:
from . import views
from django.urls import path
from django.conf.urls import include
urlpatterns = [
path('', views.PostList.as_view(), name='home'),
path('about_me/', views.Aboutme.as_view(), name='aboutme'),
path('portfolio/', views.Portfolio.as_view(), name='portfolio'),
path('posts/<slug:the_slug>/', views.PostDetail.as_view(), name='post_detail'),
path('summernote/', include('django_summernote.urls')),
]
# to jest dla wysiwyg
# add condition in django urls file
from django.conf import settings
from django.conf.urls.static import static
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
Questions:
why link is changing 2nd time when I click?
why I am getting this error after 3rd click?

Hey :) the paths /portfolio/ and /portfolio/portfolio/ are correct, but when you use htm href='portfolio/' without forward slash they are not absolute. html just add it to existing one. So if u in example.com/portfolio/ and click this href you adds another 'portfolio/'.
just use in href :
<a class="nav-link text-black font-weight-bold" href="{% url 'blog:portfolio' %}">
PS. in urls.py for project you don't need two paths to the same app

Related

How to refer a html file in templates subdirectory in <a href='url' tag in Django html template

I am quite new to django, the below is my project templates folder structure
templates
index.html
about.html
contact.html
\student
index.html
\Attendance
attendance.html
....
\Exams
results.html
exam1.html
.....
\Misc
\teachers
index.html
\hrms
adminlogin.html
payslip.html
principallogin.html
....
....
urs.py:
urlpatterns = [
path('admin/', admin.site.urls),
path("",home,name="home"),
views.py:
def home(request):
return render(request, 'index.html')
till now this is working fine, if I
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div class="u-custom-menu u-nav-container">
<ul class="u-nav u-spacing-30 u-unstyled u-nav-1"><li class="u-nav-item"><a class="u-border-0 u-border-no-bottom u-border-no-left u-border-no-right u-border-no-top u-button-style u-nav-link u-text-active-palette-1-base u-text-grey-90 u-text-hover-palette-1-base" href="{% url 'home' %}" style="padding: 20px 5px;">Home</a>
</li><li class="u-nav-item"><a class="u-border-0 u-border-no-bottom u-border-no-left u-border-no-right u-border-no-top u-button-style u-nav-link u-text-active-palette-1-base u-text-grey-90 u-text-hover-palette-1-base" href="about.html" style="padding: 20px 5px;">About</a>
</li><li class="u-nav-item"><a class="u-border-0 u-border-no-bottom u-border-no-left u-border-no-right u-border-no-top u-button-style u-nav-link u-text-active-palette-1-base u-text-grey-90 u-text-hover-palette-1-base" href="contact.html" style="padding: 20px 5px;">Contact</a>
</li><li class="u-nav-item"><a class="u-border-0 u-border-no-bottom u-border-no-left u-border-no-right u-border-no-top u-button-style u-nav-link u-text-active-palette-1-base u-text-grey-90 u-text-hover-palette-1-base" href="" style="padding: 20px 5px;">Login</a>
<div class="level-2 u-nav-popup u-white u-nav-popup-1">
<ul class="u-h-spacing-20 u-nav u-popupmenu-items u-unstyled u-v-spacing-10 u-nav-2">
<li class="u-nav-item"><a class="u-button-style u-nav-link" href="/hrms/adminlogin.html">Administrator</a></li>
<li class="u-nav-item"><a class="u-button-style u-nav-link" href="/hrms/mangementlogin.html">Management</a></li>
<li class="u-nav-item"><a class="u-button-style u-nav-link" href="/hrms/principallogin.html">Principal</a></li>
<li class="u-nav-item"><a class="u-button-style u-nav-link" href="/teacher/index.html">Teacher</a></li>
<li class="u-nav-item"><a class="u-button-style u-nav-link" href="/student/index.html">Student</a></li>
</ul>
</div>
</li>
</ul>
</div>
</body>
</html>
We are getting the following error message when we run the project, need help fixing the issue.
Not Found: /hrms/adminlogin.html
[01/Nov/2022 10:50:06] "GET /hrms/adminlogin.html HTTP/1.1" 404 4299
Not Found: /hrms/mangementlogin.html
[01/Nov/2022 10:50:06] "GET /hrms/mangementlogin.html HTTP/1.1" 404 4359
Not Found: /hrms/principallogin.html
[01/Nov/2022 10:50:06] "GET /hrms/principallogin.html HTTP/1.1" 404 4362
Not Found: /teacher/index.html
[01/Nov/2022 10:50:06] "GET /teacher/index.html HTTP/1.1" 404 4338
Not Found: /student/index.html
[01/Nov/2022 10:50:06] "GET /student/index.html HTTP/1.1" 404 4344
what we need to give in the anchor tag i.e <a href= in html template to open the specified html page in templates subdirectories i.e file mentioned in the below project templates folder structure
templates
index.html
about.html
contact.html
\student
index.html <-- this file
\Attendance
attendance.html <-- this file
....
\Exams
results.html
exam1.html
.....
\Misc
\teachers
index.html
\hrms
adminlogin.html
payslip.html
principallogin.html
....
....
tried as mentioned above
Instead of
<li class="u-nav-item"><a class="u-button-style u-nav-link" href="/hrms/adminlogin.html">Administrator</a></li>
Add this
<li class="u-nav-item"><a class="u-button-style u-nav-link" href="/hrms/adminlogin/">Administrator</a></li>
Now create views and urls for every page you want to render because Django have inbuilt template loader library.
ulrs be like
urlpatterns = [
path('admin/', admin.site.urls),
path("",home,name="home"),
path("adminlogin/",adminlogin,name="adminlogin"),
and views be like
def home(request):
return render(request, 'index.html')
def adminlogin(request):
return render(request, 'hrms/adminlogin.html')

CSS not applied to the HTML page (Django)

index.html
I have changed {% static "/main/css/index.css" %} to {% static "main/css/index.css" %}
{% extends 'main/base.html' %}
{% load static %}
<link rel = 'stylesheet' type="text/css" href="{% static "/main/css/index.css" %}"/>
{% block title %}
{{title}}
{% endblock %}
{% block content %}
<body>
<div class="grid-wrapper">
<header class="grid-header">
<img class="circles" src="{% static "main/img/main8.jpg" %}" alt="main pic">
<p>hello</p>
</header>
</div>
</body>
{% endblock %}
index.css
.grid-wrapper {
display: grid;
grid-template-columns: 1 fr;
grid-template-rows: 1 fr;
grid-template-areas: 'header header';
}
.circles {
display: block;
margin-left: auto;
margin-right: auto;
}
header {
position: relative;
width: 100%;
}
p {
color: red;
text-align: center;
position: absolute;
width: 100%;
text-align: center;
top: 0;
}
settings.py
STATIC_URL = 'static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "main/static"),
]
I tried changing file names, changing locations, connecting in a different way, but all this does not work. I also changed the settings.
This is an example of my configurations:
settings.py
STATIC_DIR = os.path.join(BASE_DIR,"static")
STATIC_URL = '/static/'
STATICFILES_DIRS = [
STATIC_DIR,
]
base.html
<!DOCTYPE html>
{%load static%}
<html lang="en">
<head>
My file structure is:
/Project
/App
/Project
/settings.py
/static
/styles.css
/templates
/base.html
You may need to share you directory structure to get further clarifications.

create two users for same sub category in a box in DJANGO

I have 4 Users(2 X CP_USER, 2 X CP_SCRNS) and two subgroups(Login stats and Application stats) but two of then belong to one group and another 2 belong to another group.
Here is the screenshot.
Database
How to separate two group and display in the html page in the same box.Here is the referenceHere is the reference how the index page shouls look like.
.
Here is my models page:
from django.db import models
from datetime import datetime
Create your models here.
class Kpi_Data(models.Model):
kpi_key = models.CharField(max_length=200,default="")
kpi_date = models.DateField(blank=True,null=True)
kpi_value = models.CharField(max_length=200,default="")
kpi_Group = models.CharField(max_length=200,default="")
kpi_subgroup = models.CharField(max_length=200,default="")
kpi_delta_ind = models.CharField(max_length=200,default="")
Here is my views.py file
from django.shortcuts import render
from django.http import HttpResponse
from .models import Kpi_Data
from django.template import loader
Create your views here.
def home(request):
return render(request,"myApp/index.html")
def info(request):
ac = Kpi_Data.objects.all()
template = loader.get_template('myApp/info.html')
Context = {
'ac': ac,
}
return HttpResponse(template.render(Context, request))
Here is my info.html page.
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/html">
<head>
<meta charset="utf-8">
<style>
</style>
</head>
<nav class="navbar navbar-expand-xl navbar-dark bg-dark">
<div class = "logo"></div>
<img src= "" width="190" height="70" alt="">
</div>
enter code here
<!-- Collection of nav links, forms, and other content for toggling -->
<div class="input-group search-box">
<input type="text" id="search" class="form-control"
placeholder="Search here...">
</div>
</form>
<div class="navbar-nav ml-auto">
<a href="#" class="nav-item nav-link active"><i1 class="fa fa-
home"></i1></a>
<div class="nav-item dropdown">
<a href="#" data-toggle="dropdown" class="nav-item nav-link
dropdown-toggle user-action active">{{ request.headers.uid }}
</br>{{ request.headers.role}}</a>
<div class="dropdown-menu">
<a href="#" class="dropdown-item"><i class="fa fa-user-o">
</i> Profile</a>
<a href="#" class="dropdown-item"><i class="fa fa-calendar-
o"></i> Calendar</a>
<a href="#" class="dropdown-item"><i class="fa fa-sliders">
</i> Settings</a>
<div class="divider dropdown-divider"></div>
<a href="#" class="dropdown-item"><i class="material-
icons"></i> Logout</a>
</div>
</div>
</div>
</nav>
<body>
<div class="sidebar">
<a class = "nav-item nav-link" href="#">Home</a>
Reference Data
`enter code here` Report Registration
Role Management
Role maintenence
User Roles
User Management
</br>
</div>
<h1>Login statistics</h1>
<h2>Appication statictics</h2>
<div class="footer fixed-bottom">
# Copyright Maryland.gov
All rights Reserved
Contatc us
Privacy & Security
Accessbility
</div>
</body>
</html>
Thanks in advance.
I see your code.
rows = Kpi_Data.objects.objects.values('kpi_group', 'kpi_subgroup',
'kpi_key').annotate(value=sum('kpi_value'))
L_C_U = L_C_S = A_C_U = A_C_S = 0`
for row in rows
if (row[kpi_Group]=='LOGIN_STATIS' and row[kpi_subgroup]='CONSUMER_PORTAL' and row[kpi_key]='CP_USER'):
L_C_U = row[value]
elif (row[kpi_Group]=='LOGIN_STATIS' and row[kpi_subgroup]='CONSUMER_PORTAL' and row[kpi_key]='CP_SCRNS'):
L_C_S = row[value]
....
Context = {
'LCU': L_C_U,
'LCS': L_C_S,
....
}
Then, in info.html, an template file, use LCU, LCS ... to display data.
I'm glad if above code would help you.

Django - unable to load static files?

Very new to Django I am trying to follow along a tutorial by sentdex over on youtube.
Django version 1.9
Chose this version as that is being used in the tutorial.
I can't seem to figure out how to get the css file to load.
The location of the css file
/media/xxx/django tutorial/mysite/personal/static/personal/css
I assume the BASE_URL is referencing till:
/media/xxx/djangotutroial/mysite
This is the location of the manage.py. Or am I wrong?
The css file is reference in header.html:
{% load staticfiles %}
<link rel="stylesheet" href="{% static 'personal/css/bootstrap.min.css' %}" type = "text/css"/>
I read through a lot of the answers and if I understand correctly I have to change settings.py in mysite folder.
This is what I have at the moment:
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR,'personal'),
]
I have tried a lot of combinations in the os.path.join I still can't get the file to load.
Thank for your help.
Project Structure:
django tutorial
--mysite
--mysite
---------__pycache_
---------__init__.py
---------settings.py
---------urls.py
---------wsgi.py
--personal
---------migrations
---------__pycache_
---------static
------personal
------css # has the bootstrap.min.css
------js
---------templates
---------admin.py
---------apps.py
---------init.py
---------models.py
---------tests.py
---------urls.py
---------views.py
If someone can tell me the right command to get the directory structure in ubuntu I would be happy to show that here.
Template:
In home.html:
{% extends "personal/header.html" %}
{% block content %}
<p>Hey, welcome to my webpage. We are testing.<p>
{% include "personal/includes/htmlsnippets.html" %}
{% endblock %}
Error message in view page source
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>Page not found at /static/personal/css/bootstrap.min.css</title>
<meta name="robots" content="NONE,NOARCHIVE">
<style type="text/css">
html * { padding:0; margin:0; }
body * { padding:10px 20px; }
body * * { padding:0; }
body { font:small sans-serif; background:#eee; }
body>div { border-bottom:1px solid #ddd; }
h1 { font-weight:normal; margin-bottom:.4em; }
h1 span { font-size:60%; color:#666; font-weight:normal; }
table { border:none; border-collapse: collapse; width:100%; }
td, th { vertical-align:top; padding:2px 3px; }
th { width:12em; text-align:right; color:#666; padding-right:.5em; }
#info { background:#f6f6f6; }
#info ol { margin: 0.5em 4em; }
#info ol li { font-family: monospace; }
#summary { background: #ffc; }
#explanation { background:#eee; border-bottom: 0px none; }
</style>
</head>
<body>
<div id="summary">
<h1>Page not found <span>(404)</span></h1>
<table class="meta">
<tr>
<th>Request Method:</th>
<td>GET</td>
</tr>
<tr>
<th>Request URL:</th>
<td>http://127.0.0.1:8000/static/personal/css/bootstrap.min.css</td>
</tr>
</table>
</div>
<div id="info">
<p>'personal/css/bootstrap.min.css' could not be found</p>
</div>
<div id="explanation">
<p>
You're seeing this error because you have <code>DEBUG = True</code> in
your Django settings file. Change that to <code>False</code>, and Django
will display a standard 404 page.
</p>
</div>
</body>
</html>
In the terminal where runserver:
[24/Feb/2019 06:19:32] "GET /static/personal/css/bootstrap.min.css HTTP/1.1" 404 1703
Error when running using #bkawan code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>Page not found at /static/personal/css/bootstrap.min.css</title>
<meta name="robots" content="NONE,NOARCHIVE">
<style type="text/css">
html * { padding:0; margin:0; }
body * { padding:10px 20px; }
body * * { padding:0; }
body { font:small sans-serif; background:#eee; }
body>div { border-bottom:1px solid #ddd; }
h1 { font-weight:normal; margin-bottom:.4em; }
h1 span { font-size:60%; color:#666; font-weight:normal; }
table { border:none; border-collapse: collapse; width:100%; }
td, th { vertical-align:top; padding:2px 3px; }
th { width:12em; text-align:right; color:#666; padding- right:.5em; }
#info { background:#f6f6f6; }
#info ol { margin: 0.5em 4em; }
#info ol li { font-family: monospace; }
#summary { background: #ffc; }
#explanation { background:#eee; border-bottom: 0px none; }
</style>
</head>
<body>
<div id="summary">
<h1>Page not found <span>(404)</span></h1>
<table class="meta">
<tr>
<th>Request Method:</th>
<td>GET</td>
</tr>
<tr>
<th>Request URL:</th>
<td>http://127.0.0.1:8000/static/personal/css/bootstrap.min.css</td>
</tr>
</table>
</div>
<div id="info">
<p>'personal/css/bootstrap.min.css' could not be found</p>
</div>
<div id="explanation">
<p>
You're seeing this error because you have <code>DEBUG = True</code> in
your Django settings file. Change that to <code>False</code>, and Django
will display a standard 404 page.
</p>
</div>
</body>
</html>
Please check if you have done first step as below
Official Documentation link for Django 1.9 link
This document is for an insecure version of Django that is no longer
supported. Please upgrade to a newer release!
Try to move on new release since documentation 1.9 is no longer supported.
Configuring static files
Make sure that django.contrib.staticfiles is included in your INSTALLED_APPS.
Check If your folder structure is similar as below
Project Structure image Link
You do not need to add code below unless if personal folder is same level as BASE_DIR
os.path.join(BASE_DIR,'personal')
Your code below is fine if you have personal app and then static folder inside personal app and then personal folder inside static folder ie personal/static/personal
{% load staticfiles %}
<link rel="stylesheet" href="{% static 'personal/css/bootstrap.min.css' %}" type = "text/css"/>
In Case if Page not found error.
Check if bootstrap.min.css exists in path personal/css/bootstrap.min.css
Check spelling as well.
Check your app ie personal in this case is included in INSTALLED_APPS
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'personal'
]
You should serve them during development. Check this part.
Edit your main urls.py(you'll find it in same folder as settings.py).
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Make sure that your app is listed in INSTALLED_APPS in django settings.
Remove /personal from your style sheet import. Instead, just have:
{%load static%}
<link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}" type = "text/css"/>
I am not sure if you copied and pasted exactly the same code but the p closing tag is out of syntax in home.html.

Links as variables arent getting passed properly from the template to urls.py to views.py

I'm trying to build a page where a YouTube player is embedded with a default video loaded. On the sidebar, I have a few pics of other videos. When one of the pics are clicked, the template reloads itself but with the YouTube player now playing the other video. Each of these pics will have a YouTube url which needs to be played when clicked. Very similar to the YouTube page of any video.
HTML:
<div class="col-md-12 col-xs-12 video_menu_item">
<div class="video_menu_description">
<a href="/library/videos/" value="https://www.youtube.com/embed/EWrT-aBDxeI" name="para">
<img src="/images/X.jpg" alt="Video name thumbnail" style="width:60%;height:100px;">
</a>
</div>
</div>
<div class="video_section_outer">
<div class="col-md-12 col-xs-12 video_scroll_track">
<div class="col-md-12 col-xs-12 video_item_outer">
<h4 class="col-md-12 col-xs-12 video_track_sub_heading"><b>video.v_name</b></h4>
<div class="col-md-12 col-xs-12 test_button_start">
<iframe width="420" height="315" src="{{ link }}" frameborder="0" allowfullscreen></iframe>
</div>
</div>
</div>
</div>
URLS.PY:
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
# Video Sections
url(r'^library/tests/', 'bt.views.tests', name='tests'),
url(r'^library/videos-(?P<link1>[\w-]+)/', 'bt.views.videos', {'link': 'para'}),
url(r'^library/videos/', 'bt.views.videos', name='videos'),
]
VIEWS.PY:
#csrf_exempt
def videos(request, link1 = "https://www.youtube.com/embed/Qj4nEYQA9ks"):
content = {"link" : link1}
return render_to_response('videos.html', content)
I think it is not ideal to pass the whole youtube url. You can make it simple by just passing the video ID as a GET parameter like this:
# urls.py
urlpatterns = [
# Video Sections
url(r'^library/tests/', 'bt.views.tests', name='tests'),
url(r'^library/videos/', 'bt.views.videos', name='videos'),
]
# views.py
def videos(request):
link = 'https://www.youtube.com/embed/{}'.format(
request.GET.get('id', 'Qj4nEYQA9ks')
)
return render_to_response('videos.html', {'link': link})
# videos.html
<a href="{% url 'videos' %}?id=EWrT-aBDxeI">
<img src="/images/X.jpg" alt="Video name thumbnail">
</a>
<iframe width="420" height="315" src="{{ link }}" frameborder="0" allowfullscreen></iframe>
Let me know if anything is not clear.