Django, not able to load image, but css is loaded - django

I m able to load css file based on the tutorial provided by djangoproject but images are not getting loaded.
Here is the file structure:
appname/static/ mess/ img/ burger.jpg
Here is the login.html file where I m trying to load the image.
`<html>
<head>
<title>Login | Mess # IIIT Sri City</title>
{% load staticfiles %}
<link rel="stylesheet" type="text/css" href="{% static 'mess/css/style.css' %}">
<link rel="stylesheet" type="text/css" href="{% static 'mess/css/bootstrap.min.css' %}">
</head>
<body>
<div class="container">
<div id="left-content" class="col-lg-6 col-md-6 col-sm-12 col-xs-12">
{% load staticfiles %}
<center><img src="{% static 'mess/img/burger.jpg' %}" alt="Please Login here"></center>
</div>
<div class="col-lg-6 col-md-6 col-sm-12 col-xs-12">
<form action="" method="post">{% csrf_token %}
{{ form}}
<input type="submit" value="Submit" />
</form>
</div>
</div>
</body>
`
It would be a great help if you could resolve me out of this issue.
PS: I m a beginner in Django.
Django version: 1.8
Please tell me if u need more info. Thanks in advance.

It was because the folder didn't have necessary permissions and Django was unable to access it.

in url.py have you configurated staticfiles?
if settings.DEBUG:
urlpatterns += patterns('',
#REMOVE IT in production phase
(r'^media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT})
)
urlpatterns += staticfiles_urlpatterns()

There are a few changes to make here. You can copy and paste the following code below for your template, and the settings below that in your urls.py:
html:
{% load staticfiles %}
<html>
<head>
<title>Login | Mess # IIIT Sri City</title>
<link rel="stylesheet" type="text/css" href="{% static 'mess/css/style.css' %}">
<link rel="stylesheet" type="text/css" href="{% static 'mess/css/bootstrap.min.css' %}">
</head>
<body>
<div class="container">
<div id="left-content" class="col-lg-6 col-md-6 col-sm-12 col-xs-12">
<center><img src="{% static 'mess/img/burger.jpg' %}" alt="Please Login here" /></center>
</div>
<div class="col-lg-6 col-md-6 col-sm-12 col-xs-12">
<form action="" method="post">{% csrf_token %}
{{ form }}
<input type="submit" value="Submit" />
</form>
</div>
</div>
</body>
</html>
urls:
if settings.DEBUG:
urlpatterns += patterns('',) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += patterns('',) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
In the html, I added {% load staticfiles %} at the top to keep your code DRY (Don't Repeat Yourself). I also made a few syntax changes to your code; very minor. In the urls, when your settings are set to DEBUG = True, Django will load your static images. When you go into production and DEBUG = False, Django no longer serves the static files. That is your server's responsibility.
I hope that helps.
If it still doesn't work, can you please post your STATIC_URL and STATIC_ROOT?

Related

Why my own css file is not loading after installation of django-cripsy-form?

I created an website using django (HTML, CSS etc). Everyithing was fine until I wanted to add a login/register form. I used django, templates. But when I installed django-crispy-forms my css was not loading anymore.
Only the register form looks good now but the other stuff like logo, menu, etc are ignoring my css.
That's how I loaded my css and it worked until django-crispy-forms
{% load static %}
<link rel="stylesheet" href="{% static 'css/style.css' %}">
<link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}">
Only below form looks good due to the django-crispy-forms package.
{% load crispy_forms_tags %}
<div class="container pt-5">
<form method="POST" class="form-group">
{% csrf_token %}
{{ form|crispy }}
<button type="submit" class="btn btn-success">Register </button>
</form>
</div>
Did you add the "CRISPY_TEMPLATE_PACK" variable in your settings.py? Also make sure you add crispy forms to your installed apps
INSTALLED_APPS = [
...
'crispy_forms',
]
CRISPY_TEMPLATE_PACK = 'bootstrap4'
Learn more about template packs here

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' %}",

how to fix NoReverseMatch at? work if you not authorized

If you are not authorized, then everything will work fine, as soon as
you authorize, for example, adeline, this error will be issued, I do
not know what happened!
NoReverseMatch at /series/Colony/Season_1/Episode_1/
Reverse for 'post_of_serie' with no arguments not found. 1 pattern(s) tried: ['series/(?P<serial_slug>[\\w-]+)/(?P<season_slug>[\\w-]+)/(?P<series_slug>[\\w-]+)/$']
main urls.py
from django.conf.urls import include, url
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^series/', include("serials.urls", namespace='series')),
url(r'^', include("serials.urls", namespace='homeview')),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
second urls.py to app(series)
from django.conf.urls import include, url
from .views import homeview, post_of_serial, post_of_season, post_of_serie, validate_email, mark_and_unmark_this_episode
urlpatterns = [
url(r'^$', homeview, name='homeview'),
url(r'^subscribe/$', validate_email, name='subscribe'), # /series/
url(r'^mark_or_unmark_this_episode/$', mark_and_unmark_this_episode, name="mark_and_unmark_this_episode"),
url(r'^(?P<serial_slug>[\w-]+)/$', post_of_serial, name='post_of_serial'), # /series/Prison_Break/
url(r'^(?P<serial_slug>[\w-]+)/(?P<season_slug>[\w-]+)/$', post_of_season, name='post_of_season'), # /series/Prison_Break/season_5/
url(r'^(?P<serial_slug>[\w-]+)/(?P<season_slug>[\w-]+)/(?P<series_slug>[\w-]+)/$', post_of_serie, name='post_of_serie'), # /series/Prison_Break/season_5/2/
]
error
this is part of view.py
def post_of_serie(request, serial_slug=None, season_slug=None, series_slug=None):
serie = get_object_or_404(Series, serial_of_this_series__slug=serial_slug, season_of_this_series__slug=season_slug, slug=series_slug)
#print(serie)
title = serie.serial_of_this_series.rus_name_of_seriall
full_path = All_Images_Of_The_Series.objects.filter(to_series__serial_of_this_series__slug=serial_slug, to_series__season_of_this_series__slug=season_slug, to_series__slug=series_slug, is_poster=True)
context = {"serie":serie, "full_path":full_path, "title":title,}
try:
userr = request.user
check_button = watched_series.objects.filter(user=request.user, watched_serial__slug=serial_slug, watched_serie__season_of_this_series__slug=season_slug, watched_serie__slug=series_slug )
context["check_button"] = check_button
context["userr"] = userr
except:
pass
return render(request, 'series.html', context)
if delete somethig in views.py nothing change!!!
main html
{% load staticfiles %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<title>{{ title }}</title>
<!-- Bootstrap -->
<link href="{% static "css/bootstrap.min.css"%}" rel="stylesheet">
<link href="{% static "css/footer.css"%}" rel="stylesheet">
<link href="{% static "css/main.css"%}" rel="stylesheet">
{% block styles %}{% endblock styles %}
</head>
<body>
<div class="advertises" ></div>
<div class="wrapper">
<div class="wrapper-content">
{% include "navbar.html" %}
{% block content %}
{% endblock content %}
</div>
{% include "footer.html" %}
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>
<script src="{% static "js/bootstrap.min.js"%}"></script>
<script src="{% static "js/smooth-scroll.js"%}"></script>
<script src="{% static "js/script.js" %}"></script>
</body>
</html>
series.html where is up error!
{% extends "base.html" %}
{% load staticfiles %}
{% block content %}
<div class="container">
<div class="row">
<div class="col-sm-8 her">
<span class="links" >
<a class="a-link" href="{{ serie.serial_of_this_series.get_absolute_url }}">{{ serie.serial_of_this_series.rus_name_of_seriall }} <img src="{% static "img/breadcrumbs-arrow.png" %}" class="arrow" > </a>
<a class="a-link" href="{{ serie.season_of_this_series.get_absolute_url }}">{{ serie.season_of_this_series.name_of_the_season }}<img src="{% static "img/breadcrumbs-arrow.png" %}" class="arrow" ></a>
<a class="a-link" href="{{ serie.get_absolute_url }}">{{ serie.rus_name }}<img src="{% static "img/breadcrumbs-arrow.png" %}" class="arrow" ></a>
</span>
<div class="title-block" >
<h3 class="seria-header">
<img src="{{ serie.serial_of_this_series.preview_of_serial.url }}" class="thumb">
<span class="titles" >
<div class="title-ru">{{ serie.rus_name }}</div>
<div class="title-en">{{ serie.eng_name }}</div>
</span>
</h3>
{% if user.is_authenticated %}
<form class="watch_button" method="POST" action="{% url 'series:post_of_serie' %}" > {% csrf_token %}
<div class="buttons" >
<div class="second_section_of_buttons" >
{% if check_button %}
<div class="isawthat-btn checcked" title="Серия просмотрена. Убрать пометку?" ><img src="{% static "img/white-eye-icon.png" %}" class="iccon"/><span class="text_button" >Серия просмотрена</span></div>
{% else %}
<div class="isawthat-btn" title="Пометить серию как просмотренную" ><img src="{% static "img/pink-eye-icon.png" %}" class="iccon"/><span class="text_button" >Серия Не просмотрена</span></div>
</div>
{% endif %}
</div>
<p class="user hidden" >{{ userr }}</p>
<p class="watched_serial hidden" >{{ serie.serial_of_this_series }}</p>
<p class="watched_serie hidden" >{{ serie }}</p>
<p class="minutes_of_series hidden" >{{ serie }}</p>
<p class="serial_slug hidden" > {{ serie.serial_of_this_series.slug }} </p>
<p class="season_slug hidden" > {{ serie.season_of_this_series.slug }} </p>
<p class="series_slug hidden" > {{ serie.slug }} </p>
</form>
{% endif %}
</div>
</div>
<div class="col-sm-3">
</div>
</div>
</div>
{% endblock content %}
<form class="watch_button" method="POST" action="{% url 'series:post_of_serie' %}" >
this is the line you are having the error bro, see, this form appears only for logged in user, and you dont have a view like def post_of_serie(request):
try to pass the slugs here in the form url, then the problem will be solved

Can't attach css files or image to Django template

Surfing the internet, I found some solutions of my problem. But it didn't help(Include CSS and Javascript in my django template) last answer.
I added this in urls.py:
urlpatterns += patterns('',
url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}),
)
This is my settings.py:
CURRENT_PATH = os.path.abspath(os.path.dirname(__file__).decode('utf-8'))
MEDIA_ROOT = os.path.join(CURRENT_PATH, 'media')
MEDIA_URL = '/media/'
STATIC_ROOT = 'static/'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(CURRENT_PATH, 'static'),
)
And my template:
<html>
<head lang="en">
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}css/main.css" />
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}css/bootstrap.min.css" />
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}css/font-awesome.min" />
<title></title>
</head>
<body>
{% load staticfiles %}
<div id="modal" class="modal fade">
<div class="modal-header">
<div>Вхід у систему</div>
</div>
<div class="modal-body">
<form action = "/login/" method="post">
<div>
<label for="username">Логін:</label>
{{form.username}}
</div>
<div>
<label for="password">Пароль:</label>
{{form.password}}
</div>
<br>
<div>
<input type="submit" value="Submit">
</div>
</form>
</div>
</div>
<img src="{{STATIC_URL}}ukraine.png" alt="My image"/>
</body>
</html>
As the result CSS files are not working and even image isn't found.
I created folder for static files: D:\KIT\static\css
Referring from official documents:
Make sure you have included django.contrib.staticfiles in INSTALLED_APPS
What is the CURRENT_PATH? Make sure it is D:\KIT\
Then you can inlcude them like this:
<link rel="stylesheet" type="text/css" href="{% static "css/main.css" %}" />
Make sure your templates start with {% load staticfiles %}
You probably forgot to run collectstatic. It's highly unpractical to run it everytime something changed while in development, so to avoid this you have to modify your settings.
Add django.contrib.staticfiles to your INSTALLED_APPS and set DEBUG=True, runserver will then do the heavy lifting for you.
I would also recommend using the static template tag {% static 'path/to/static.css' %} over {{ STATIC_URL }} and placing templatetag loading on the first line (second line if you're extending your template) of your template file.

How to override default django forgot password template?

The password reset templates are stored in:
/usr/local/lib/python2.7/dist-packages/django/contrib/admin/templates/registration
However, I want to override the default templates provided my Django. I don't want to directly go to that directory and edit the template. Thus, I created password reset templates with same name in templates/registration directory. However, I am still getting the same inbuild django template. My one template password_reset_form.html looks like this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>ATS | Password Reset Form</title>
<!--google web font-->
<link href='http://fonts.googleapis.com/css?family=Droid+Serif:400,400italic,700|Lato:700,300,400' rel='stylesheet' type='text/css'>
<!--style sheets-->
<link rel="stylesheet" media="screen" href="{{ STATIC_URL }}bootstrap/css/bootstrap.css"/>
<link rel="stylesheet" media="screen" href="{{ STATIC_URL }}bootstrap/css/style.css"/>
<link rel="stylesheet" media="screen" href="{{ STATIC_URL }}bootstrap/css/static.css"/>
<style>
li
{
list-style-type: none;
padding: 0px;
margin: 0px;
}
#footer {
margin-top: 40px;
}
</style>
<!--jquery libraries / others are at the bottom-->
<script src="{{ STATIC_URL }}bootstrap/js/jquery-1.7.1.min.js" type="text/javascript"></script>
</head>
<body>
<!-- Header starts
================================================== -->
<header id="header">
<div class="container">
<div class="row">
<!--logo starts-->
<div class="span4"> <img src="{{ STATIC_URL }}bootstrap/img/auto.png"> </div>
<!--logo ends-->
</div>
</header>
<div class="container">
<h2 class="lead text-center">Password Reset</h2><br /> <br />
<form action="" class="well span10" method="post">
{% csrf_token %}
{% block content %}
<p class="text-info text-center"><strong>Forgotten your password? Enter your e-mail address below, and we'll e-mail instructions for setting a new one.</strong></p>
<span class="text-error text-center"><strong> {{ form.email.errors }}</strong></span><br/>
<p class="text-center"><label for="id_email">Enter your E-mail address:</label> {{ form.email }}</p>
<p class="text-center"><button class="btn btn-success">Reset my Password</button></p>
</form>
{% endblock %}
</div>
<footer id="footer">
<div class="container">
<div class="row">
<!--small intro and copyright starts-->
<div class="span7">
<a data-toggle="tab" href="/how_it_works/">How it works? </a>
<a data-toggle="tab" href="/how_it_works/">Terms and Conditions </a>
<a data-toggle="tab" href="/how_it_works/">How to use? </a> <br /><br />
<p class="copyright"> ©2013 Automatic Text Summarization(ATS) </p>
</div>
Is there something I am missing in the template?
Have you placed your template in your apps directory? If so specify your app before django.contrib.admin in INSTALLED_APP setting.
If you have placed the template in some other folder, verify you have appropriately added the directory in TEMPLATE_DIRS and in filesystem loader is before _app_directories _loader in TEMPLATE_LOADERS.
So it should be
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
)
More reference at Template loaders