Django static files not serving in DetailView - python

Trying to create a Profile View in the app I just started. I can't seem to figure out this simple issue I'm having though. When I load my index page or any other page that doesn't have a pk, everything loads correctly. However, whenever I attempt to load a page that has something like /profile/1/ in the url, the staticfiles won't load. I keep getting a 404. Please help! My code is rather long already, but I'll break it down. I'll add my settings, urls, and views, and profile page. I can't think of anything else that would be needed at this time.
Settings.py:
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATE_DIR = os.path.join(BASE_DIR, 'dispatch/templates')
STATIC_DIR = os.path.join(BASE_DIR, 'dispatch/static')
MEDIA_DIR = os.path.join(BASE_DIR, 'dispatch/media')
STATIC_URL = '/static/'
STATICFILES_DIRS = [STATIC_DIR]
MEDIA_ROOT = MEDIA_DIR
MEDIA_URL = '/media/'
URLS.py at Project level
from django.conf.urls import url, include
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'', include('dispatch.urls', namespace='dispatch')),
url(r'^admin/', admin.site.urls),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
URLS.py at App Level:
# SET THE NAMESPACE!
app_name = 'dispatch'
# Be careful setting the name to just /login use userlogin instead!
urlpatterns=[
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^profile/(?P<pk>\d+)/$', views.ProfileDetailView.as_view(), name='profile_detail'),
]
Views.py
class ProfileDetailView(DetailView):
context_object_name = 'profile_detail'
model = models.UserProfile
template_name = 'pages/profile.html'
pages/profile.html
{% extends 'lib/base.html' %}
{% load staticfiles %}
{% block page_css %}
<link rel="stylesheet" type="text/css" href="{% static 'vendors/css/extensions/pace.css' %}">
<link rel="stylesheet" type="text/css" href="{% static 'css/pages/users.css' %}">
{% endblock %}
{% block content %}
<div align="right">
<p>{{ profile_detail.user }}</p>
<p>{{ profile_detail.zipcode }}</p>
<img src="{{ profile_detail.profile_image }}" alt="Profile Image">
</div>
{% endblock %}
Error from manage.py Note the /profile/1/ in the path
[12/Jun/2017 20:40:04] "GET /profile/1/static/css/core/menu/menu-types/vertical-menu.css HTTP/1.1" 404 2570
[12/Jun/2017 20:40:04] "GET /media/CACHE/images/profile_images/20170612_110531/7d87ed0f89df89bff1d122fbf82bb83d.jpg HTTP/1.1" 304 0
Not Found: /profile/1/profile_images/20170612_110531.jpg
[12/Jun/2017 20:40:04] "GET /profile/1/profile_images/20170612_110531.jpg HTTP/1.1" 404 2525

Related

Unable to Dynamically Render Django images on templates

So I've been trying to get the images uploaded through admin interface to render on a template but for some odd reason it just wont render the images. It renders any other type of data but NOT IMAGES.
From Settings.py:
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
From appvew.py:
class ProjectsListView(ListView):
model = Projects
context_object_name = 'projects'
template_name = 'myportfolio/portfolio.html'
appurls.py:
urlpatterns =[
path('home/', views.ProjectsListView.as_view()),
# path('projects/', )
]
html template:
{% load static %}
</head>
<body>
<h1><p>This is my portfolio</p></h1>
{% for project in projects %}
<img src="{{project.screenshot}}" alt="No image found">
{% endfor %}
</body>
</html>
Error message on the terminal:
Not Found: /portfolio/home/projects/images/shutterstock_253580635_square.jpg
Not Found: /portfolio/home/projects/images/mountains.jpg
[25/Mar/2022 14:16:06] ←[33m"GET /portfolio/home/projects/images/shutterstock_253580635_square.jpg HTTP/1.1" 404 2560←[0m
[25/Mar/2022 14:16:06] ←[33m"GET /portfolio/home/projects/images/mountains.jpg HTTP/1.1" 404 2500←[0m
output :( :
I verified an old project of mine with pretty much the same set up and it works. This one on the other hand, only renders the name of the objects on other properties but not the images
Try this
<img src="{{project.screenshot.url}}" alt="No image found">
https://docs.djangoproject.com/en/4.0/topics/files/

How to show model images in Django?

I have such models.py file
class Product(models.Model):
CATEGORIES = {
('Computer', 'Комп\'ютер'),
('Smartphone', 'Смартфон')
}
photo = models.ImageField(upload_to='images/', blank=True)
title = models.CharField(max_length=128, blank=False)
description = models.CharField(max_length=5000, blank=False)
price = models.PositiveIntegerField(blank=False)
category = models.CharField(max_length=30, choices=CATEGORIES)
count = models.PositiveIntegerField(blank=False)
In settings.py i DON'T have media variables/dirs
Also i try to show images in such way
{% extends 'base.html' %}
{% block title %}Каталог{% endblock %}
{% block content %}
{% for i in products %}
<img src="{ static i.photo.url }">
{{i.title}}
{% endfor %}
{% endblock %}
Result:
I add my model objects in Django Admin
please see below configuration, have you done?
urls.py
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# urls/path
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
your HTML file
{% if i.photo %}
<img src="{{ i.photo.url }}">
{% endif %}
You don't need the static tag.
<img src="{{ i.photo.url }}">
You can add like this.
and run the collectstatic command to
<img src="{% static '/logo.png' %}"/>
python manage.py collectstatic
In settings.py i DON'T have media variables/dirs
you have to set MEDIA_ROOT and MEDIA_URL in settings.py and set the URL of each in urls.py because by default, Django stores files locally, using the MEDIA_ROOT and MEDIA_URL settings. The examples below assume that you’re using these defaults.
check the official doc.
step - 1
configure media and static files like this
add this in your settings.py
STATIC_ROOT = BASE_DIR / 'static_cdn'
STATIC_URL = '/static/'
MEDIA_ROOT = BASE_DIR / 'media'
MEDIA_URL = '/media/'
STATICFILES_DIRS = [
BASE_DIR / "static",
]
and add this in your urls.py
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

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}}

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

static url path setting in django

I am new to django, presently I am learning and trying to build a basic site with django-cms. Below are my project folder structure and code files
project_folder
manage.py
main_folder
static
css
new-styles.css
js
new-styles.js
templates
base.html
home.html
media
pic_1.gif
.....
settings.py
urls.py
.......
settings.py
import os
PROJECT_DIR = os.path.abspath(os.path.dirname(__file__))
DEBUG = True
MEDIA_ROOT = os.path.join(PROJECT_DIR,'media')
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(PROJECT_DIR,'static')
STATIC_URL = '/static/'
TEMPLATE_DIRS = (os.path.join(PROJECT_DIR,'templates'))
TEMPLATE_CONTEXT_PROCESSORS = (
'django.contrib.auth.context_processors.auth',
'django.core.context_processors.i18n',
'django.core.context_processors.request',
'django.core.context_processors.media',
'django.core.context_processors.static',
'django.core.context_processors.debug',
'django.contrib.messages.context_processors.messages',
'cms.context_processors.media',
'sekizai.context_processors.sekizai',
)
......
.......
urls.py
from django.conf.urls import patterns, include, url
from django.conf import settings
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^$', ...........),
)
if settings.DEBUG:
urlpatterns = patterns('',
url(r'^media/(?P<path>.*)$', 'django.views.static.serve',{'document_root': settings.MEDIA_ROOT, 'show_indexes': True}),
url(r'', include('django.contrib.staticfiles.urls')),
) + urlpatterns
base.html
{% load cms_tags sekizai_tags menu_tags %}
<html>
<head>
<title>{%block "title" %}{% endblock %}</title>
<link rel="stylesheet" href="{{ STATIC_URL }}css/new-styles.css">
{% render_block "css" %}
</head>
<body>
{% cms_toolbar %}
{% block "base_content" %}
{% endblock %}
{% render_block "js" %}
</body>
</html>
home.html
{% extends "base.html" %}
{% load cms_tags %}
{% block "title" %}Welcome to Services{% endblock %}
{% block "base_content" %}
<p>Hi this is paragraph</p>
<img src="{{ MEDIA_URL }}images/promo3.jpg" />
{% placeholder "number_one" %}
{% endblock %}
new-styles.css
body {
padding:0px; margin:0px; margin-top:40px;
background-color:#b0c4de;
}
p {
background-color:#e0ffff;
}
So above are my complete project structure and code files, but my actual problem is new-styles.css file is not working, even though I had written some css code in the file it is not linking to the template, so can anyone please let me know whats wrong and why base.html template file is unable to access the new-styles.css file, whether the path given in link tag is wrong or the path setting in the settings.py is wrong?
urls.py
from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from project_name import settings
admin.autodiscover()
urlpatterns = patterns('',
.....................
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += staticfiles_urlpatterns()

Categories

Resources