can't get image to load - django

I probably did something stupid but when i upload a image with /admin I can't get it to load.
I made a for loop to get all post's and everything shows except for the image
model:
`class Post(models.Model):
title = models.CharField(max_length=140)
body = models.TextField()
image = models.ImageField(upload_to='blog/media/photos')
date = models.DateTimeField()`
template page:
` {% for post in object_list %}
<h5>{{post.title}}</h5>
<img src="{{ post.image.url }}">
<h1>{{ post.image.url }}</h1>
{% endfor %}`

I would imagine it is related to your MEDIA_URL settings. Check the terminal output and look for the request to the image, there is a good chance you've not set that, and/or you've not added the media url handler to your urls.
https://docs.djangoproject.com/en/2.0/howto/static-files/#serving-files-uploaded-by-a-user-during-development

You must set the media folder path in the settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
MEDIA_URL = '/media/'
or add media root on url.py
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = patterns('',
# ... the rest of your URLconf goes here ...
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Is there a blog/media/photos folder path and accessable?

Related

Upload a file in admin and then download from the website Django

I am trying to create a website, where customer can upload a file in an Admin section, and after any person can download this file from the website. Preferably any files like pdf, exe, doc (is it possible?) I am able to upload a file in Admin and it shows it on the website. It downloads the file with a correct name (saved in media) but shows a failure , file missing.
So far I have :
setting.py
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
models.py
class TEACHING(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
date_posted = models.DateTimeField(auto_now_add=True)
excercise = models.FileField(upload_to="files/", default='default value')
def __str__(self):
return self.title
views.py
def teaching(request):
context = { 'teaches' : TEACHING.objects.all()}
return render(request, 'blog/teaching.html', context)
urls.py
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root = settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
teaching.html
{% for teach in teaches %}
<a href="{{ teach.excercise }}" download>Download</a>
{% endfor %}
Managing files docs
You should get URL from your File field
<a href="{{ teach.excercise.url }}" download>Download</a>
Hi You are not providing url in href, so please change your <a> with following way
<a href="{{ teach.excercise.url }}" download>Download</a>

Django - Images won´t be displayed in template, but image url showes up. Urls.py Issue?

Using Django 2.1.5 + Bootstrap 4.2 and some Icons from fontawesome
Hello ,
after a long search I decided to post, because most answer are related to older Django versions.
I am relatively new to Django and I like to test all the Function/Class Views and Modelfields. Now I wanted to test how I can display images linked with my database in my template. But unfortunately, images want not display, all I see is image placeholder icon.
I created an app and 2 simple models, with musicians (with images) and cars. The upload via admin works and the blank url are accessible in the Template via {{ modelone.person_pic }}
PROBLEMS SOLVED - See down Below
aquaman / models.py
class Person(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
person_pic = models.ImageField(upload_to='artist/', max_length=255, null=True, blank=True )
def __str__(self):
return "{} - {}".format(self.first_name[:25], self.last_name[:25])
class Data_Sheet(models.Model):
car = models.CharField(max_length=30)
color = models.CharField(max_length=30)
def __str__(self):
return "{} - {}".format(self.car[:25], self.color[:25])
views.py
from django.shortcuts import get_object_or_404, render, redirect
from django.utils import timezone
from django.views.generic.list import ListView
from django.views.generic import TemplateView
from .models import Person, Data_Sheet
<…some other views…>
class ArtistView4(TemplateView):
template_name = 'aquaman/artistview4.html'
def get_context_data(self, **kwargs):
context = super(ArtistView4, self).get_context_data(**kwargs)
context['modelone'] = Person.objects.all()
context['modeltwo'] = Data_Sheet.objects.all()
return context
artistview4.html
{% extends 'base.html' %}
{% load static %}
{% block custom_css %}
<link rel="stylesheet" type="text/css" href="{% static 'css/clear_styles.css' %}">
{% endblock %}
{% block content %}
{% for visual in modelone %}
<div align="center">
<h4 class="">{{ visual.first_name }}</h4>
<h4 class="">{{ visual.last_name }}</h4>
<h4 class="">{{ visual.person_pic }}</h4> <!-- to check if url is displayed -->
</div>
<img src="{{ visual.person_pic.url }}">
</div>
{% endfor %}
{% endblock %}
urls.py
from django.urls import path
from . import views
from .views import AquaListView, AquaListView2, AquaListView3, ArtistView4
app_name='aquaman'
urlpatterns = [
path('home/', views.aqua_home, name='aqua_home'),
path('aqua_listview/', AquaListView.as_view(), name='aqua_listview'),
path('aqua_listview2/', AquaListView2.as_view(), name='aqua_listview2'),
path('aqua_listview3/', AquaListView3.as_view(), name='aqua_listview3'),
path('arstistview4/', ArtistView4.as_view(), name='artistview4'),
]
my approach
As far as I understand the documentation. I have to add this lines to the urls.py in the urlpattern, so that everything gets directed.
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
So my urls.py looks like this now
from django.urls import path
from django.conf import settings
from django.conf.urls.static import static
from . import views
from .views import AquaListView, AquaListView2, AquaListView3, ArtistView4
app_name='aquaman'
urlpatterns = [
path('home/', views.aqua_home, name='aqua_home'),
path('aqua_listview/', AquaListView.as_view(), name='aqua_listview'),
path('aqua_listview2/', AquaListView2.as_view(), name='aqua_listview2'),
path('aqua_listview3/', AquaListView3.as_view(), name='aqua_listview3'),
path('arstistview4/', ArtistView4.as_view(), name='artistview4'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
This is what i added in my settings.py
TEMPLATES = [
{
<…>
'django.template.context_processors.media',
<…>
},
]
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
'/var/www/static/',
]
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
So far nothing changed. Django shows me the last name correctly in the template, but I only see image place holders and no images.
Django Server
Not Found: /media/artist/freddy_mercury.jpg
Not Found: /media/artist/kurt_cobain.jpg
Not Found: /media/artist/ella_fitzgerald.PNG
Not Found: /media/artist/amy_winehouse.PNG
[07/Feb/2019 18:42:49] "GET /media/artist/ella_fitzgerald.PNG HTTP/1.1" 404 2257
When i upload a image via admin from my desktop Django automatically saves the pictures in **MyProject/media/artist>** but at the same time django can not find these images?
If go directly to the images via http://127.0.0.1:8000/media/artist/kurt_cobain.jpg for example, django shows me this:
The current path, media/artist/kurt_cobain.jpg, didn't match any of these.
Even though Django puts the picture via upload in the BaseDir/media/artist folder.
Maybe I missed the "Serving files in development" aka if settings.DEBUG:
https://docs.djangoproject.com/en/2.1/ref/views/
But when I add this also nothing happens.
I really like to thank everyone, who might have a hint
Problem Solved
Alright, I misunderstand something in the Docs maybe it´s not so obvious.
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [...] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
This has to be added in the "MainApp/urls.py" not in your "MyOtherApps/urls.py". I thought just because I only need Images in a specific app I have to add these lines in these specific App urls.py.
Rock On & Peace

saving image files in django model

i want to store a lot of images in a table(model of django) under an attribute 'imgsrc'. How do i do that? i have seen a lot of online material but i am not getting the complete information anywhere. What changes do i need to do in settings.py and where do i store my image files?...
a part of models.py
class elementdetails(models.Model):
sid=models.IntegerField()
imgsrc=models.ImageField()
soundsrc=models.FileField()
sounddesc=models.CharField(max_length=20)
Setup MEDIA_ROOT and MEDIA_URL in you settings.py:
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
In your urls.py, add:
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Make sure to have media directory in your root directory.
Now, you can also use uploaded_to in your model for storing those images in a directory.
class elementdetails(models.Model):
sid=models.IntegerField()
imgsrc=models.ImageField(upload_to='elements/')
soundsrc=models.FileField()
sounddesc=models.CharField(max_length=20)
In order to get the image in templates, use:
<img src="{{ object.imgsrc.url }}" alt="image">
If you want to upload images in forms, make sure to use enctype="multipart/form-data" in template:
<form action="" method="post" enctype="multipart/form-data">
Also, make sure in views, use:
form = Form(request.POST, request.FILES)
It will work.

How to add a file from a filefield in Django to urls and views?

I'm doing a Django project, and I have a model called Projects, in this model I have a FileField inwhich files get uploaded to /media/files/YEAR/MONTH/DATE/.
settings.py:
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
models.py:
class Project(models.Model):
...
file_upload = models.FileField(upload_to='files/%Y/%m/%d', max_length=100, null=True, blank=True, default='')
template:
...
{% if project.file_upload %}
<tr>
<td>File</td>
<td>{{ project.file_upload.name }} (Size: {{ project.file_upload.size|filesizeformat }})</td>
</tr>
{% endif %}
...
Now a link to a file would be something like: /media/files/2016/05/25/picture.png or /media/files/2016/05/25/report.pdf
Currently I get a 404 page not found, whenever I click the link. That is ofcourse because the path is not in the urls.py, but since you usually add a view to an url, I don't know how you would do it with a single file, as it would seem to me a view wouldn't be necessary.
How do I tell Django in urls (And possibly in views) how to get that file? I want to be able to click the link and then either view the picture/pdf in the browser or simply download the file.
Django does not serve static files. To force these files to be served when DEBUG=True, add this code to urls.py:
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
(from https://docs.djangoproject.com/en/1.9/howto/static-files/#serving-static-files-during-development)
You do not need to tell Django about static files in views.py

Displaying uploaded media in a web page

Friends,
I am using Django 1.6 and I have for the last week(!) been trying to display photos on a web page that are uploaded via the Django Admin site.
I know this is a common problem. I have tried reading the documentation, numerous SO questions like this one and this one all without success.
After uploading the image via the Admin site, I can see that the image exists in the following folder:
/home/ian/django/mysite/cars/media/images/1.JPG
However when the page loads (or trying to view the image after uploading them via the Admin Site) I see a 404 error. The source for the image shows the following:
<li><img src="/media/images/1.JPG" height="420"/></li>
The model.py has the following field:
photo = models.ImageField(upload_to='images/')
The urls.py has the following added:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
The template is:
{% extends "base.html" %}
<h1>Here</h1>
<p>{{ collectiondetail.title }}</p>
{% for photo in photos %}
<li><img src="{{ photo.photo.url }}" height="420"/></li>
{% endfor %}
{% endblock %}
Finally the settings.py are:
STATIC_ROOT = '/home/ian/django/mysite/cars/static/'
STATIC_URL = '/static/'
MEDIA_ROOT = '/home/ian/django/mysite/cars/media/'
MEDIA_URL = '/media/'
What have I missed?
The urls.py snippet you are using is only for development and will only work in debug mode. Everything you have looks correct so double-check that in settings.py DEBUG = True. From the docs on this feature:
This helper function works only in debug mode and only if the given prefix is local (e.g. /media/) and not a URL
Thanks to everyone for helping out. The default permissions when the files were uploaded were ok.
Finally managed to track down the problem to two settings.
MEDIA_URL was previously set to:
MEDIA_URL = '/media/'
Changed this to:
MEDIA_URL = '/cars/media/'
Changed the following in the urls.py file from
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
to
if settings.DEBUG:
urlpatterns += patterns('',
url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT,
}),
url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.STATIC_ROOT,
}),
)
And now the images show as expected.