I only see the file path in the template. I can't see the file itself.
(django 3.x)
settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
model.py
class EkleModel (models.Model):
aKaydi = models.CharField(max_length=50, verbose_name='A KAYDI')
bKaydi = models.CharField(max_length=50, verbose_name='B KAYDI')
cKaydi = models.CharField(max_length=50, verbose_name='C KAYDI')
upload = models.FileField(upload_to='media/%Y/%m/%d/', verbose_name='DOSYA YÜKLE')
yuklemeTarihi =models.DateTimeField(default =timezone.now)
views.py
def index(request):
girdiler = EkleModel.objects.filter(yuklemeTarihi__lte=timezone.now()).order_by('-yuklemeTarihi')
return render(request, 'sayfalarUygulamasi/index.html', {'girdiler': girdiler})
index.html
<img class="card-img-top" src="girdi.upload">
<h4 class="card-title">{{girdi.aKaydi}}</h4>
<h4 class="card-title">{{girdi.bKaydi}}</h4>
<h4 class="card-title">{{girdi.cKaydi}}</h4>
<h4 class="card-title">{{girdi.yuklemeTarihi}}</h4>
you have to loop through your queryset and .url to the image
{% for girdi in girdiler %}
<img class="card-img-top" src="{{ girdi.upload.url }}">
<h4 class="card-title">{{girdi.aKaydi}}</h4>
<h4 class="card-title">{{girdi.bKaydi}}</h4>
<h4 class="card-title">{{girdi.cKaydi}}</h4>
<h4 class="card-title">{{girdi.yuklemeTarihi}}</h4>
{% endfor %}
<img class="card-img-top" src="girdi.upload.url"> #add url after fieldname like this
try this
{% for girdi in girdiler %}
<img class="card-img-top" src="{{me.upload.url}}">
{% endfor %}
and to your model
class EkleModel (models.Model):
upload = models.FileField(upload_to='image/', null=True, blank=True,FileField)
urls.py
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
...
]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns +=static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
and do migrations
Related
Django can be able to display the image if I comment out the product details page.
I would like to know why it does that and how can I make it always display the images.
Product model
item_name = models.CharField(max_length=20)
item_description = models.TextField(
max_length=200, verbose_name="Item Description")
item_price = models.FloatField(default=0.00)
slug = models.SlugField(null=True, unique=True)
item_details = models.TextField(
max_length=1000, verbose_name="Item Details")
item_quantity = models.IntegerField(default=0)
item_availability = models.BooleanField(default=False)
is_item_featured = models.BooleanField(default=False)
is_item_recommended = models.BooleanField(default=False)
# Todo: add Is On Carousel Filter
item_brand = models.ForeignKey(Brand, null=True, on_delete=models.CASCADE)
item_categories = models.ForeignKey(
Category, null=True, on_delete=models.CASCADE)
item_image = models.ImageField(upload_to='images/product/',
default="images/product/image-placeholder-500x500.jpg")
Product Views
class HomePageView(ListView):
model = Product
template_name = 'product/index.html'
class ProductListView(ListView):
model = Product
template_name = 'product/product_list.html'
def product_detail(request, slug):
objec = get_object_or_404(Product, slug=slug)
template_name = 'product/product_detail.html'
return render(request, template_name, context={'object': objec})
Product Templates
{% for product in object_list %}
<div class="col-md-3 col-sm-6">
<div class="product-grid4">
<div class="product-image4">
<a href="product/{{ product.slug }}">
<!-- <img src="{{ product.item_brand.brand_image.url }}" alt="{{ product.item_brand.brand_name }}" width="30px"> -->
<img class="pic-1" src="{{ product.item_image.url }}" alt="{{ product.item_name }}">
</a>
<!-- <span class="product-new-label">Recommended</span> -->
<!-- <span class="product-discount-label">-10%</span> -->
</div>
<div class="product-content">
<h3 class="title">{{ product.item_name }}</h3>
<div class="price">
Kshs. {{product.item_price }}
<!-- <span>$16.00</span> -->
</div>
<a class="add-to-cart" href="{% url 'add-to-cart' product.slug %}">ADD TO CART</a>
</div>
</div>
</div>
{% endfor %}
Product Urls
url(r'product/(?P<slug>.+)$', views.product_detail, name='product-detail'),
url('^$', views.HomePageView.as_view(), name='landing_page'),
url('shop/', views.ProductListView.as_view(), name="product-list")
Settings.py
.....
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.0/howto/static-files/
STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles")
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
]
# Simplified static file serving.
# https://warehouse.python.org/project/whitenoise/
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
The error I get. Please note the error only comes up when product_detail view and it's url are called. When they are commented out, the images are displayed.
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/media/images/product/airmax_98_bVXgZPB.jpg
Raised by: shop.views.product_detail
No Product matches the given query.
If you don't want have problems when you change urlpattern, you should replace <a href="product/{{ product.slug }}"> to <a href="{{ product.get_absolute_url }}"> and add a bit of code to models.py
*product fields goes here*
def get_absolute_url(self):
return reverse('product-detail', args=[self.slug])
And don't forget from django.urls import reverse
I've noticed that your django is not pretty new, and if Can not import reverse from django.urls
The problem is with how the url is being displayed.
I should Use path instead of url like so:
Product Urls
......
path('product/<slug>/', views.product_detail, name='product-detail'),
path('shop/', views.ProductListView.as_view(), name="product-list"),
......
I still don't have a clear understanding as to why I should use path instead of url
I'm having issues serving images based on the ImageField in Django.
models.py part looks like that:
class Post(models.Model):
author = models.ForeignKey(Author, on_delete=models.CASCADE)
category = models.ManyToManyField(Category)
trip = models.ForeignKey(Trip, on_delete=models.CASCADE)
main_image = models.ForeignKey(Image, on_delete=models.CASCADE, related_name='main_image')
images = models.ManyToManyField(Image, related_name='images')
class Image(models.Model):
name = models.CharField(max_length=32)
picture = models.ImageField(upload_to='pictures/', blank=True)
trip = models.ForeignKey(Trip, on_delete=models.CASCADE)
taken = models.DateTimeField(blank=True, null=True)
uploaded = models.DateTimeField(default=timezone.now)
def __unicode__(self):
return self.name
settings.py contains the MEDIA_URL and MEDIA_ROOT:
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
Also included what I've found in other SO topics in the urls.py:
from django.contrib import admin
from django.urls import path, include
from django.conf.urls import url
from django.contrib.staticfiles.urls import static, staticfiles_urlpatterns
from django.conf import settings
from markdownx import urls as markdownx
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('blog.urls')),
url(r'^markdownx/', include('markdownx.urls')),
] + staticfiles_urlpatterns() + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
In the end I put it in the html template like that:
{% extends 'blog/base.html' %}
{% block leftcolumn %}
{% for post in posts %}
<div class="leftcolumn">
<div class="card" style="max-width: 100%">
<h2>{{ post.title }}</h2>
<h5>published: {{ post.published_date }}, by: {{ post.author }}</h5>
<div><img src="{{ post.main_image.url }}"></div>
<p>{{ post.byline }}</p>
</div>
</div>
{% endfor %}
{% endblock %}
But the image is not shown..
I can see the image if I go to the url host:8000/media/pictures/test_photo.jpgand in general I can display images on the page (e.g. within django-markdownx field) but not through ImageField url.
Any ideas what's wrong here?
This line:
<div><img src="{{ post.main_image.url }}"></div>
should be:
<div><img src="{{ post.main_image.picture.url }}"></div>
The reason is your model Image does not have an url method. The method belongs to the ImageField, in this case picture.
To be clear, I have tried researching this on my own but since I'm still very new to Django I am unable to understand the solutions here. I also have read the documentation and I don't understand what I'm doing wrong. I cannot get the images located in the "ad_pictures" directory to display in the HTML.
Here's my code:
settings.py
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
urls.py (project)
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'^admin/', admin.site.urls),
url(r'^accounts/', include('accounts.urls')),
url(r'^classifieds/', include('classifieds.urls')),
] +static(settings.MEDIA_URL, document_ROOT=settings.MEDIA_ROOT)
urls.py (classifieds app)
from django.conf.urls import url
from . import views
app_name = 'classifieds'
urlpatterns = [
url(r'^create/', views.create, name='create'),
url(r'^latestads/', views.latestads, name='latestads'),
]
models.py
class Post(models.Model):
title = models.CharField(max_length=150)
price = models.CharField(max_length=100)
body = models.TextField()
pub_date = models.DateTimeField(null=True)
author = models.ForeignKey(User, null=True)
category = models.CharField(max_length=150, null=True)
picture = models.ImageField(upload_to='ad_pictures', default='')
latestads.html
{% for post in posts.all %}
<div class="advertisements">
<div class="a-title">
<h3>{{ post.title }}</h3>
</div>
<div class="a-image">
<img src="{{ post.picture.url }}">
</div>
<div class="a-content">
<p>{{ post.body }}</p>
</div>
<div class="a-date">
<p>{{ post.pub_date }} by {{ post.author }}</p>
</div>
</div>
<img src="{{ post.image.url }}">
{% endfor %}
Picture of directory structure:
here
Html output:
here
I'm sure part of the problem is the "post.picture.url" in the HTML.
Any insight is greatly appreciated.
Thanks
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^accounts/', include('accounts.urls')),
url(r'^classifieds/', include('classifieds.urls')),
] +static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
please change document_ROOT to document_root
I hope you can help me withmy Django project. I am able to upload an images under a media_cdn folder, inside a folder based on the name of the slug. The problem occurs when I try to display the image inside my post list and post.
Can you please have a look at my code and offer a solution. I spent hours trying to get it to work. Please help.
settings.py
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
MEDIA_URL = "/media/"
MEDIA_ROOT = os.path.join(BASE_DIR, 'media_cdn/')
models.py
def upload_location(instance, filename):
return "%s/%s" %(instance.slug, filename)
class Post(models.Model):
category = models.ForeignKey(Category)
title = models.CharField(max_length=250)
slug = models.SlugField(max_length=250, unique=True)
image = models.ImageField(upload_to=upload_location,
null=True,
blank=True,
width_field="width_field",
height_field="height_field")
height_field = models.IntegerField(default=0)
width_field = models.IntegerField(default=0)
body = models.TextField()
date = models.DateTimeField()
updated = models.DateTimeField(auto_now=True)
postlist.html
{% block content %}
{% for post in posts %}
<div class="container w3-card-4">
{% if post.image %}
<img src="{{ post.instance.image.url }}">
{% endif %}
...
post.html
{% block content %}
<div class="row">
<div class="container w3-card-4">
{% if instance.image %}
<img src= "{{ instance.image.url }}" class="img-responsive">
{% endif %}
...
url.py
from django.conf.urls import include, url
from django.contrib import admin
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', include('personal.urls')),
url(r'^blog/', include('blog.urls', namespace='blog', app_name='blog')),
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
I don't know what else to try to call that image from the folder. Any advice would be greatly appreciated. Thank you!
Use post.image.url instead of post.instance.image.url. Check the documentation.
ImageField inherits all the attributes of the FileField which includes url.
Have a problem, try to do simple gallery in django, but when i tried to check how it looks, picture doesn't show anything only title name and there is at terminal "Error 404 not found". Can't realise what actually is wrong... Please help. thx...
Not Found: /media/images/example.png
[16/Mar/2016 17:59:17] "GET /media/images/example.png HTTP/1.1" 404 2168
models.py
class Album(models.Model):
title = models.CharField("Название альбома", max_length=100)
slug = models.SlugField("Ссылка на альбом", max_length=100, unique=True)
img = models.ImageField("Изображение альбома", upload_to='images',
help_text='Размер изображения 200px на 200px')
created_date = models.DateTimeField(default=timezone.now)
published_date = models.DateTimeField(blank=True, null=True)
class Photo(models.Model):
title = models.CharField("Название фотографии", max_length=100)
album = models.ForeignKey(Album, related_name='Альбом')
img = models.ImageField("Фото", upload_to='images',
help_text='Желательно не большой размер')
urls.py - app
from django.conf.urls import url
from django.conf import settings
from django.conf.urls.static import static
from django.views.generic import ListView, DetailView
from .models import Album, Photo
urlpatterns = [
url(r'^$', ListView.as_view(
model=Album,
context_object_name='my_album',
template_name='gallery/album.html'),
name='gallery'
),
url(r'^(?P<slug>[-\w]+)/$', DetailView.as_view(
model=Album,
context_object_name='photos',
template_name='gallery/photo.html'),
name='photo'
),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
urls.py - project
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^gallery/', include('gallery.urls')),
]
settings.py
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
template
{% extends "gallery/base.html" %}
{% load thumbnail %}
{% block title %}My Gallery{% endblock %}
{% block text %}
{% for album in my_album %}
<a href='{{ album.slug }}'>
<img src="{{ album.img.url}}" alt="{{ album.title }}">
<!-- {% thumbnail album.img "200x200" crop="center" as im %}
<img src="{{ im.url }}" alt="{{ im.title }}" width="{{ im.width }}"
height="{{ im.height }}">
{% endthumbnail %} -->
</a>
{% endfor %}
{% endblock %}
ProjectStructure
ProjectFolder/
app/
migrations/
static/
templates/
admin.py
models.py
..
project/
settings.py
urls.py
..
media/
images/
example.png
my_env/
manage.py
if in setting.py i do MEDIA_URL = 'media/images' it will work, but only for album template if you will go to see album photos, there photo won't shows too with the same error... Actually i can't understand and realise how to do access to folder media and just bring any of content placed here what i need. Help me...