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}}
Related
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 am trying to load an image from a folder within 'media' folder (media/tshrirts) onto template using django. Below is my settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
]
MEDIA_URL = '/media/'
#MEDIA_ROOT = os.path.join(BASE_DIR,'media')
MEDIA_ROOT = 'media'
**I tried both the roots none of them work.
Below is my models.py
from django.db import models
# Create your models here.
class tshirts(models.Model):
brand=models.CharField(max_length=50)
name=models.CharField(max_length=100)
price=models.DecimalField(max_digits=10, decimal_places=2)
image = models.ImageField(upload_to='tshirts/')
def __str__(self):
return self.name
this is part of the tshirts.html Why image.url is none??
<div class='tshirts'>
{% for eachtshirt in alltshirts %}
<div class='tshirt'>
{{eachtshirt.brand}}
<p>{{eachtshirt.name}}</p>
<p>{{eachtshirt.price}}</p>
<img src="{{eachshirt.image.url}}"/>
{% if eachshirt.image.url == None %}
<p>{{"Image Not Found"}}</p>
{% endif %}
</div>
{% endfor %}
</div>
finally, urls.py
urlpatterns = [
.
.
.
url(r'^tshirts/',include('tshirts.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
After I uploaded the image as an admin and clicked the link, the image was properly displayed.
http://127.0.0.1:8000/media/tshirts/t-shirt2.jpg - the image was displayed here.
How can I fix this, please let me know thanks!!!
Screenshot for the page
The root of your media, should include the BASE_DIR, like the following:
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
MEDIA_URL = '/media/'
You have a typo in your template, you'are accessing {{eachshirt.image.url}} without t. the correct is
{{eachtshirt.image.url}} <!-- with t : each tshirt -->
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
\project_structure
-app
\project
-settings.py
-...
\picture
-panda.jpg
I've uploaded the picture into picture.
class Goods(models.Model):
pic = models.ImageField(upload_to='picture')
And the data in database is picture/panda.jpg
Now,how can i show it in html?
I wrote this in html:
<p>{{each.pic}}</p>
<img src='{{ each.pic.url }}' />
And the source codes in browser is this:
picture/panda.jpg
<img src='picture/panda.jpg' />
The image was linked to http://localhost:8000/my_sell/picture/panda.jpg.And couldn't show.
How can i solve this,I've tried add media_root in settings.py and useless.
I did not check this but almost all code are taken from my working projects :).
settings.py:
MEDIA_URL = '/media/'
MEDIA_ROOT = (
os.path.join(BASE_DIR, 'media')
)
models:
from django.core.files.storage import FileSystemStorage
from django.conf import settings
image_storage = FileSystemStorage(
# Physical file location ROOT
location=u'{0}/my_sell/'.format(settings.MEDIA_ROOT),
# Url for file
base_url=u'{0}my_sell/'.format(settings.MEDIA_URL),
)
def image_directory_path(instance, filename):
# file will be uploaded to MEDIA_ROOT/my_sell/picture/<filename>
return u'picture/{0}'.format(filename)
class Goods(models.Model):
pic = models.ImageField(upload_to=image_directory_path, storage=image_storage)
views:
from django.shortcuts import render
def view_picture(request):
c = dict()
c['goods'] = Goods.objects.all()
return render(request, 'template.html', c)
templates:
{% for product in goods %}
{% if product.pic %}
<img src="{{ product.pic.url }}">
{% endif %}
{% endfor %}
Edited: Don't forget to add MEDIA_URL into root urls.py
if settings.DEBUG
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
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