Django Will Not Open Up Static File Image, Django 3 - python

So I have been trying to figure out why the image will not show and I have watched and read numerous things, but i still can't find anything. This is my first question on here. Thanks for helping out
HTML
{% load static %}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Nikhil's Portfolio</title>
</head>
<body>
test
<img scr="{% static 'static/homepage/wpap.jpg' %}" alt="why is it not working">
<img scr="{% static 'static/homepage/download.jpg' %}" alt="why is it not working">
</body>
</html>
url.py of my website (not app url)
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('homepage.urls'))
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
How my files are arranged
img of file organization

Try this
{% static 'homepage/wpap.jpg' %}
Instead of
{% static 'static/homepage/wpap.jpg' %}

It would need to change from this:
<img scr="{% static 'static/homepage/wpap.jpg' %}" alt="why is it not working">
To this:
<img src="{% static 'static/homepage/wpap.jpg' %}" alt="why is it not working">
The "scr" would change to "src"

Related

Django 404 css file

For a long time I tried to solve the problem with loading all my static files. When I found a working solution, all svg started loading, but css files didn't.
Here is my settings.py (showing you only main things)
import mimetypes
mimetypes.add_type("text/css", ".css", True)
BASE_DIR = Path(__file__).resolve().parent.parent
DEBUG = False
STATIC_URL = '/static/'
if DEBUG: STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
else: STATIC_ROOT = os.path.join(BASE_DIR, 'static')
Here is my urls.py
from django.contrib import admin
from django.urls import path, include
from django.conf.urls import url
from django.conf import settings
from django.views.static import serve
urlpatterns = [
path('', include('main.urls')),
url(r'^static/(?P<path>.*)$', serve,{'document_root': settings.STATIC_ROOT}),
]
Here is an example of using css files in my templates
{% load static %}
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-v4-grid-only#1.0.0/dist/bootstrap-grid.min.css">
<link rel="stylesheet" type="text/css" href=" {% static 'css/reset.css' %}">
<link rel="stylesheet" type="text/css" href=" {% static 'css/main.css' %}">
And this is the error in Chrome Console
Refused to apply style from '<URL>' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.
And also i cant open css files in a new tab. I am getting that error
Also, if you remove %20 from the address bar, then I will open the css file
P.S.
I am trying to deploy it
1- Try to replace a slash forward path
<link rel="stylesheet" type="text/css" href=" {% static '/css/reset.css' %}">
2- whitenoise
pip install whitenoise
Then, set it to "MIDDLEWARE" in "settings.py". Finally, CSS is loaded successfully:
MIDDLEWARE = [
# ...
"django.middleware.security.SecurityMiddleware",
"whitenoise.middleware.WhiteNoiseMiddleware", # Here
# "whitenoise" will solve "MIME type" error then CSS is loaded successfully:
]
3- change your static URL like that:
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)
I think your mistake is that you put in a space in front of your static link
<link rel="stylesheet" type="text/css" href=" {% static 'css/reset.css' %}">
Try removing the space in front of {% so it will become
<link rel="stylesheet" type="text/css" href="{% static 'css/reset.css' %}">
%20 is translated to a space character in URL's, so that why I think that's the issue

I can't see ImageField's photos in DJango's view [Solve]

something fail in my Django project, because the images that I load in the imagefields don't show in the view.
https://www.dropbox.com/sh/fvx6sfmxgm08xo6/AABVR-AQGeF52pCxlzVaLuDaa?dl=0
The crab's photo it's load with "static", but the second, that it's imagefield's photo.
enter image description here
Model:
class foto(models.Model):
nombre=models.CharField(max_length=50)
imagen=models.ImageField(upload_to='fotos/')
def __str__(self):
return self.nombre
View:
def general(request):
lista=foto.objects.all()
context={'material':lista}
return render(request,'indice.html',context)
settings:
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
STATICFILES_DIRS = (
'/media/fotos/',
)
html:
{% load staticfiles %}
<html>
<head>
<title>Album de fotos</title>
</head>
<body>
<img src="{% static 'cangrejo.jpg' %}" />
{% if material %}
{% for a in material %}
<li>{{a.nombre}}: {{a.imagen}}</li>
<img src="{{a.imagen}}" />
{% endfor %}
{% else %}
<p>No hay fotos</p>
{% endif %}
</body>
</html>
Admin's URLS:
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'',include('colecion.urls')),
]
View's URLS:
from django.conf.urls import url, include
from colecion import views
urlpatterns =[
url(r'^$',views.general),
]
Edit: I already solve the problem!
settings.py
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'ciencia/static')
models.py
foto=models.ImageField()
html
<img src="{% static alfa.foto %}" />
From the docs:
MEDIA_URL - "Absolute filesystem path to the directory that will hold user-uploaded files."
MEDIA_ROOT - "URL that handles the media served from MEDIA_ROOT, used for managing stored files. It must end in a slash if set to a non-empty value. You will need to configure these files to be served in both development and production environments."
Your current config's MEDIA_URL doesn't look right. It should be a URL, you have it set to a filesystem path. Try something like
MEDIA_URL = '/media/'
Add this to urls.py
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Change {{a.imagen}} to {{a.imagen.url}}

Python 2.7 Django 1.9 static files administration error

I am trying to solve this for 2 hours now. I tried everything I read every post but I think I am still missing something. My static files are not loading. I am getting this error when I click to static files url path on browsers view-source page. "A server error occurred. Please contact the administrator." Before this error It was fine in this index page; 127.0.0.1:8000/ But when I try to go on 127.0.0.1:8000/home it was still same index page but it wasn't loading static files because it was looking static files at home/ directory. So I decided to make my static urls dynamic. I though I was not making mistake but Pycharm says unresolved template reference to this;
<script src="{% static 'jquery.min.js' %}"></script>
<script src="{% static 'bootstrap.min.js' %}"></script>
<script src="{% static 'retina-1.1.0.js' %}"></script>
<script src="{% static 'jquery.hoverdir.js' %}"></script>
<script src="{% static 'jquery.hoverex.min.js' %}"></script>
<script src="{% static 'jquery.prettyPhoto.js' %}"></script>
<script src="{% static 'jquery.isotope.min.js' %}"></script>
<script src="{% static 'custom.js' %}"></script>
at the begining of the page I used
{% load static from staticfiles %}
this peace of code. How can ı fix these problems guys I need your help!
Debug = true
urls.py
from django.conf.urls import url, include
from . import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^home/$', views.index, name = 'home'),
url(r'^$', views.index, name= 'index'),
url(r'^second/$', views.second, name = 'second'),
]
if settings.DEBUG:
urlpatterns +=[
url(r'^static/(?P<path>.*)$', 'django.views.static.serve',
{'document_root', settings.STATIC_ROOT}
),
]
Settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'basic/static'),
)
STATIC_ROOT = os.path.join(BASE_DIR, 'assests/')
Within the django docs for 1.9 the stated way of serving static files during development is to use the following:
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)
Along with the following in your templates:
{% load staticfiles %}
<img src="{% static "my_app/myexample.jpg" %}" alt="My image"/>
Have you tried using this method of serving static files whilst in debug?

TemplateDoesNotExist. loading static files and templates Django project structure

I am a bit confused on how to yield templates from other apps
Here is a picture of my project structure:
I am getting this error:
TemplateDoesNotExist at /
home.html
home/views.py:
class HomeView(generic.TemplateView):
template_name = "home.html"
Settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),
os.path.join(BASE_DIR, "home/static/home/js"),
os.path.join(BASE_DIR, "home/static/home/images"),
os.path.join(BASE_DIR, "home/static/home/css"),
)
TEMPLATE_DIRS = (
os.path.join(BASE_DIR, 'templates'),
)
project/home/urls.py:
from django.conf.urls import patterns, url
from home.views import HomeView
urlpatterns = patterns('',
url(r'^$', HomeView.as_view(), name="home"),
)
project/urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'', include("home.urls", namespace="home")),
)
project/templates/home/index.html
<!DOCTYPE html>
<html>
<head lang="en">
...
<!-- Fonts -->
<link href='http://fonts.googleapis.com/css?family=Lobster' rel='stylesheet' type='text/css'>
<!-- Custom CSS -->
<link href="{{ STATIC_URL }}boothie.css" rel="stylesheet">
<!-- Custom JS-->
<script src="{{ STATIC_URL }}boothie.js"></script>
<title>Boothie</title>
</head>
<body>
<div class="container">
...
</div>
</head>
{% block content %}{% endblock %}
</body>
</html>
project/home/templates/home/home.html:
{% extends index.html %}
{% block content %}
...
<script src="{{ STATIC_URL }}js/jquery.easing.1.3.js"></script>
<script src="{{ STATIC_URL }}js/boothie.js"></script>
{% endblock %}
Django stops at the first template that it finds matching the requested filename, and it will start at the templates directory in the app folder.
If it doesn't find it here, it will then go up the chain till it has searched all locations in the TEMPLATE_DIRS setting, and only then will it print an error that it cannot find a template. The way it searches for templates is defined by the TEMPLATE_LOADERS setting.
In your project layout, the template you want is located in the template directory of the home app, and inside this directory, under the home directory. Thus the template path should be home/home.html in your view:
class HomeView(generic.TemplateView):
template_name = "home/home.html"
If your templates directory is in your project's root you have to add it to setitngs.py
If it's the subdirectory of an app (that is in INSTALLED_APPS in settings.py) then the app template loader (enabled by default) will load it.
If your app is called home then you would have the templates dir inside the home dir, not home under templates which would make it accessible as home/home.html since it's under the home subfolder of the templates dir in settings.py

Image does not appear Django template

I am trying to load some images into a template but it continues to appear as broken link
My files and directories are as follows
1.views.py
def home(request):
#template = loader.get_template("polls/home.html")
return render_to_response('polls/home.html',
context_instance=RequestContext(request))
2.urls.py
urlpatterns = patterns('',
#url(r'^applications/', include('polls.urls')),
url(r'^admin/', include(admin.site.urls)),
(r'^', include('polls.urls')),
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
3.home.html
{% load staticfiles %}
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>psdtowebSimpleWebsiteTemplate.psd</title>
<link href="{% static 'C:\Users\omars_000\Desktop\mytask\polls\templates\polls\styles.css' %}" rel="stylesheet" type="text/css">
</head>
<body>
<div id="background">
<div id="background"><img src="{{MEDIA_URL}}/Capture.png"></div>
</body>
</html>
4.settings.py
MEDIA_ROOT = os.path.join( PROJECT_DIR, 'media')
MEDIA_URL = '/media/'
STATIC_ROOT = ''
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(PROJECT_DIR, "static"),
'/var/www/static/',
)
Any idea why it is not working? I have checked many questions but nothing helped so far.
Your MEDIA_URL already has a trailing slash. You are adding another in <img src="{{MEDIA_URL}}/Capture.png"> Most browsers don't care, but perhaps yours does.
Got it.
In home.html I fixed to be as follows:
<div id="background"><img src="{% static "C:\Users\omars_000\Desktop\mytask\mytask\media\images\background.png" %}""></div>
and in settings.py I added the location of the images i will be using in the template as follows:
STATICFILES_DIRS = (
'C:\Users\omars_000\Desktop\mytask\mytask\media\images',
'C:\Users\omars_000\Desktop\mytask\mytask\media',
)

Categories

Resources