Can't get images to work in django - django

I'm getting a 404 error when trying to serve user uploaded files in local. I've tried a lot of suggestions from the forums but I can't get it to work.
This is the error I can see on the logs. The images get uploaded properly to media/images but when I try to use that same image I get a 404 not found. I've tried to put the absolute path and didn't work either. Could anybody please help me? Thanks
[03/Feb/2018 23:32:00] "GET /idealistos/30/ HTTP/1.1" 200 483
Not Found: /media/images/_D3L8637.jpg
[03/Feb/2018 23:32:01] "GET /media/images/_D3L8637.jpg HTTP/1.1" 404 2239
settings.py
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static')
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
# Media files
MEDIA_ROOT = 'media/'
MEDIA_URL = '/media/'
models.py
from django.db import models
from django.forms import ModelForm
from django.utils import timezone
from django.contrib.admin.widgets import AdminDateWidget
# Create your models here.
class Anuncio(models.Model):
title = models.CharField(max_length=40)
description = models.CharField(max_length=300)
price = models.CharField(max_length=10)
city = models.CharField(max_length=20)
state = models.CharField(max_length=20)
country = models.CharField(max_length=20)
postcode = models.CharField(max_length=20)
foto = models.FileField(null=True, blank=True, upload_to='images/')
pub_date = models.DateTimeField(default=timezone.datetime.now())
def __str__(self):
return self.title
def __unicode__(self):
return price
class AnuncioForm(ModelForm):
class Meta:
model = Anuncio
fields = ['title', 'description', 'price', 'city', 'state', 'country','postcode','foto']
views.py
from django.http import Http404, HttpResponseRedirect
from django.views.generic import ListView
from django import forms
from django.utils import timezone
#from django.template import loader
from django.shortcuts import render, get_object_or_404, redirect
from .models import Anuncio, AnuncioForm
#Creates a list from a model. Used for the ad index view.
class AnuncioList(ListView):
model = Anuncio
#Creates a detail view of the Ad
def detail(request, anuncio_id):
try:
anuncio_detalle = get_object_or_404(Anuncio, pk=anuncio_id)
#anuncio_detalle = Anuncio.objects.get(pk=anuncio_id)
except Anuncio.DoesNotExist:
raise Http404("Question does not exist")
return render(request, 'idealistos/detail.html', {'anuncio_detalle':anuncio_detalle})
def add_form(request):
if request.method == 'POST':
form = AnuncioForm(request.POST,request.FILES)
if form.is_valid():
new_add = form.save()
new_add.pub_date = timezone.now()
return redirect ('idealistos:index')
else:
form = AnuncioForm()
return render(request, 'idealistos/create_add.html', {'form':form,})
url.py
from django.conf.urls.static import static
from django.conf import settings
from django.urls import path
from . import views
from idealistos.views import AnuncioList
app_name ='idealistos'
urlpatterns = [
# ex: /idealistos/
path('', AnuncioList.as_view(), name='index'),
# ex: /idealistos/5/
path('<int:anuncio_id>/', views.detail, name='detail'),
#ex: /idealistos/add_form
path('add_form/', views.add_form, name='add_form'),
]
urlpatterns+=static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
Template
<head>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">
</head>
<body>
{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'idealistos/idealistos.css' %}" />
<h1>{{ anuncio_detalle }}</h1>
<ul>
<li>{{ anuncio_detalle.description }}</li>
<li>{{ anuncio_detalle.city }}, {{ anuncio_detalle.country }} CP:{{ anuncio_detalle.postcode }}</li>
<li>{{ anuncio_detalle.pub_date }}</li>
<img src={{anuncio_detalle.foto.url}}>
</ul>
</body>

Just try giving MEDIA_ROOT and serving in urls.py when DEBUG=True.
models.py
foto = models.ImageField(upload_to='images/', null=True, blank=True)
settings.py
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'media')
MEDIA_URL = '/media/'
urls.py
from django.conf.urls import url, include
from django.contrib import admin
from django.views.static import serve
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
#Other Urls
. . . . .
. . . . .
# admin
url(r'^admin/', admin.site.urls),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
if settings.DEBUG:
urlpatterns += [
url(r'^media/(?P<path>.*)$', serve, {
'document_root': settings.MEDIA_ROOT
}),
]

I hope that you are seeing the uploaded file correctly.
For local development, try adding the following in your base urls.py
if settings.DEBUG is True:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Related

Download BinaryFiled Data

how to download BinaryField Data/file using template. like we did for FileField.
<td><a href={{certificate.bytes.url}} download></a>
I past all url.py and view.py file below please look This may give extract view of my code. and please help me with this i am new to Django. ............................................................................................................................................................
url.py
from django.conf.urls.static import static
from django.conf.urls import url
from django.views.defaults import page_not_found
urlpatterns=[
path('',views.index, name = 'index'),
url(r'^list/$', views.list, name='list'),
url(r'^list/create$', views.certificate_create, name='certificate_create'),
url(r'^list/(?P<id>\d+)/update$', views.certificate_update, name='certificate_update'),
url(r'^list/(?P<id>\d+)/delete$', views.certificate_delete, name='certificate_delete'),
path('download',views.download, name = 'download'),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
So, we need Django models which contains BinaryField for example.
models.py
class Person(models.Model):
name = models.CharField(max_length=55)
surname = models.CharField(max_length=55)
image = models.BinaryField()
class Meta:
db_table = 'person'
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('download/<int:pk>/', views.download, name='download'),
]
views.py
import io
from django.shortcuts import render
from django.http import FileResponse
from .models import Person
def index(request):
# there are listed all models.
persons = Person.objects.all()
return render(request, 'index.html', {'persons': persons})
def download(request, pk):
# this url is for download
try:
obj = Person.objects.get(pk=pk)
except Person.DoesNotExist as exc:
return JsonResponse({'status_message': 'No Resource Found'})
get_binary = obj.image
if get_binary is None:
return JsonResponse({'status_message': 'Resource does not contian image'})
if isinstance(get_binary, memoryview):
binary_io = io.BytesIO(get_binary.tobytes())
else:
binary_io = io.BytesIO(get_binary)
response = FileResponse(binary_io)
response['Content-Type'] = 'application/x-binary'
response['Content-Disposition'] = 'attachment; filename="{}.png"'.format(pk) # You can set custom filename, which will be visible for clients.
return response
index.html
{% for person in persons %}
{{ person.name }}<br />
{% endfor %}
This is solution to send binary file from server and download. All components are shown. Good luck !

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

problems in constructing webmap using django leaflet with the data in database

I have done my leaflet program using django-leaflet but the map is not displaying anything in output
Here is the code
models.py
from django.db import models
from django.contrib.gis.db import models as gismodels
class MushroomSpot(gismodels.Model):
title = models.CharField(max_length=256)
id1=models.IntegerField(primary_key=True)
geom = gismodels.PointField()
objects = gismodels.GeoManager()
def __unicode__(self):
return self.title
urls.py
from django.conf import settings
from django.conf.urls import url
from django.conf.urls.static import static
from django.contrib import admin
from django.views.generic import TemplateView
from djgeojson.views import GeoJSONLayerView
from .models import MushroomSpot
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', TemplateView.as_view(template_name='index.html'), name='home'),
url(r'^data.geojson$', GeoJSONLayerView.as_view(model=MushroomSpot), name='data'),
]
index.html
{% load leaflet_tags %}
<html>
<head>
{% leaflet_js %}
{% leaflet_css %}
</head>
<body>
<h1>Weather Stations</h1>
{% leaflet_map "main" callback="main_map_init" %}
<script type="text/javascript">
function main_map_init (map, options) {
var dataurl = '{% url "data" %}';
// Download GeoJSON via Ajax
$.getJSON(dataurl, function (data) {
// Add GeoJSON layer
L.geoJson(data).addTo(map);
});
}
</script>
</body>
</html>
contents related to leaflet in settings.py
DATABASES = {
'default': {
'ENGINE': 'django.contrib.gis.db.backends.spatialite',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
SPATIALITE_LIBRARY_PATH = 'mod_spatialite'
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR
LEAFLET_CONFIG = {
'DEFAULT_ZOOM': 6,
'MIN_ZOOM': 1,
'MAX_ZOOM': 20,
}
And I run the setup.py file which has
import csv
from django.contrib.gis.geos import Point
from mushrooms.models import MushroomSpot
csv_file = 'mycsv.csv'
def dms2dec(value):
"""
Degres Minutes Seconds to Decimal degres
"""
degres, minutes, seconds = value.split()
#seconds, direction = seconds[:-1], seconds[-1]
dec = float(degres) + float(minutes)/60 + float(seconds)/3600
#if direction in ('S', 'W'):
# return -dec
return dec
reader = csv.DictReader(open(csv_file), delimiter=",")
for line in reader:
lng = dms2dec(line.pop('mlong'))
lat = dms2dec(line.pop('mlat'))
wmoid = int(line.pop('id'))
name = line.pop('place').title()
print(lng,lat)
MushroomSpot(id1=wmoid, title=name, geom=Point(lng, lat)).save()
Please help me in getting the output map in screen
I dont know what is the error in it
The csv file contains the data of about 8 cities in india
And I want the desired India map as an interactive webmap
Please let me to my desired output

Django video in template, seems to detect media but not working

Please i have been working on this for a while but don't seem to find the problem. I am trying to get a video from the uploaded files to work on the template,but all i keep getting is a blank video, although when i view the page source or inspect the video element, it seems to be pointing to the right video, and all solutions i have tried to make this work proved abortive.
Below are my codes:
MY MODEL:
class Sermon(models.Model):
topic = models.CharField('Topic', max_length=50)
pub_date = models.DateField('Sermon Date')
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
last_edited = models.DateTimeField(auto_now_add=False, auto_now=True)
type = models.CharField('Type', max_length=50, choices=sermon_chioices)
audio = models.FileField(upload_to='audios', default="Not Available", blank=True, validators=[validate_audio_extension], null=True)
video = models.FileField(upload_to='videos', default="Not Available", blank=True)#can be changed if the video will recide in the system
outlines = models.FileField(upload_to="outlines", default="Not Available", blank=True,)
user = models.ForeignKey(User, verbose_name="User", editable=False)
class Meta:
ordering = ['-pub_date']
def __unicode__(self):
return self.topic
def get_absolute_url(self):
#return reverse('sermon_detail', kwargs={'pk': self.pk})
return reverse('sermon_detail', args=[str(self.id)])
MY VIEW:
class SermonDetails(DetailView):
model = Sermon
template_name = 'agonopa/sermon_details.html'
context_object_name = 'sermon'
def get_context_data(self, **kwargs):
context = super(SermonDetails, self).get_context_data(**kwargs)
#context['sermons'] = Sermon.objects.all()
return context
#Sunday Service List
class SundayServiceSermonList(ListView):
model = Sermon
template_name = 'agonopa/sermon.html'
context_object_name = 'sermon_list' #'ss_sermon_list'
queryset = Sermon.objects.filter(type__exact="SUNDAY SERVICE")
def get_context_data(self, **kwargs):
context = super(SundayServiceSermonList, self).get_context_data(**kwargs)
context['title'] = 'Sunday Service'
return context
MY TEMPLATE:
{% if sermon %}
<h3>{{ sermon.topic}}</h3>
{{sermon.outline}}
{{ sermon.pub_date}}
{% endif %}
<video loop class="embed-responsive-item thumbnails" controls>
<source src="{{ MEDIA_URL}}{{sermon.video.url}}" type="video/mp4">
</video>
MY MEDIA SETTINGS:
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
PROJECT_DIR = os.path.dirname(BASE_DIR)
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(PROJECT_DIR,'churchsite_static_root','media_root')
The Server returns things like this in the terminal:
[28/Nov/2015 11:38:10]"GET /agonopa/sermon/3/ HTTP/1.1" 200 377
[28/Nov/2015 11:38:10]"GET /media/videos/wowo_Boyz_5gQAbzG.mp4 HTTP/1.1" 404 2344
Thanks for your help in advance, and for further clarification on the question pls do let me know.
It should be noted, that i have tried many solutions from stakeoverflow, and several blogs but none seems to works, so i had to post it here.
It seems to me that your MEDIA_ROOT is way too high (as in no longer within your project). When I use the settings you use, I get a media root directory of ../../../churchsite_static_root/media_root/ relative to your settings.py file. I would expect churchsite_static_root to be one directory up from settings.py (or at the same level as manage.py).
Go into Django shell and check the media root path to see if it seems reasonable (and confirm that your files are actually there):
python manage.py shell
>>> from django.conf import settings
>>> settings.MEDIA_ROOT
Try the following in your settings.py and let me know if it helps:
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
MEDIA_ROOT = os.path.join(BASE_DIR, 'churchsite_static_root', 'media_root')
Be sure you have something like this in your site's urls.py if using python manage.py runserver:
# For Django>=1.8:
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
# For Django<1.8:
if settings.DEBUG:
urlpatterns += patterns('',
(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT}))
I simply imported settings, and then static, and also added the if Debug: to my urls.py, thus the program looked as below:
Urls.py:
from django.conf.urls import include, url, patterns
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from agonopa.views import SermonMonthArchiveView, SermonYearArchiveView
urlpatterns = [
# Examples:
# url(r'^$', 'churchsite.views.home', name='home'),
url(r'^$', 'agonopa.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^agonopa/', include('agonopa.urls')),
url(r'^grappelli/', include('grappelli.urls')),
url(r'^admin/', include(admin.site.urls)),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
That's all to it. Thanks to Mike Covington in all.
Also note, that the media settings, template and other files above didn't change for the whole stuff to work.

Image from database doesn't display in a django template even though the image is available when right-clicked "save as"

I'm on development server and I'm trying to display an image in a template uploaded by user.
The image doesn't display even though it seems available to be saved. When I right-click "Save as", file name pops up in the window.
When I try to save the file to the hard drive it gives an error though.
I checked the media folder and it seems models work fine - pictures were uploaded to the media folder as intended. Also, I'm able to retrieve other data from database(chars, integers) - I only struggle with pictures.
I have revived all questions related to image upload available on stackexchange, and made lots of small changes to my code - but nothing seems to help me.
models.py
from django.db import models
class Lesson(models.Model):
phrase = models.CharField(max_length=200)
progress_bar = models.DecimalField(max_digits=5, decimal_places=2)
lesson_slug = models.SlugField(max_length=50)
def __unicode__(self):
return self.phrase
class Lesson_Options(models.Model):
lesson = models.ForeignKey(Lesson)
option1_photo = models.ImageField(upload_to='images/')
option1_voice = models.FilePathField(path="/media/user123/Elements/Projects/PENCIL/lesson/voice/", recursive=True)
option1_photo_description = models.CharField(max_length=200)
views.py
def detail(request, lesson_id):
le_objects = Lesson.objects.get(pk=lesson_id)
me_options = Lesson_Options.objects.get(pk=lesson_id)
lesson = le_objects.progress_bar
display_test = me_options.option1_photo
return render(request, 'lesson/detail.html', {'lesson': lesson, 'display_test': display_test})
urls.py (Project urls)
from django.conf.urls import patterns, include, url
from django.conf import settings
from django.conf.urls.static import static
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^lesson/', include('lesson.urls')),
url(r'^admin/', include(admin.site.urls)),
)
urls.py (Application urls)
from django.conf.urls import patterns, url
from django.conf import settings
from django.conf.urls.static import static
from lesson import views
urlpatterns = patterns('',
# ex: /lesson/
url(r'^$', views.index, name='index'),
# ex: /lesson/5/
url(r'^(?P<lesson_id>\d+)/$', views.detail, name='detail'),
# ex: /lesson/5/results/
url(r'^(?P<lesson_id>\d+)/results/$', views.results, name='results'),
)
settings.py
MEDIA_ROOT = '/media/user123/Elements/Projects/PENCIL/lesson/media/'
MEDIA_URL = '/media/'
detail.html
<li class="span4"> <a class="thumbnail"> <img alt="hello"
src="{{ display_test }}" height="300" width="300" class="option1" id="incorrect_answer1"></a> </li>
HTML Output
<img alt="hello" src="images/girl_1.jpg" height="300" width="300" class="option1" id="incorrect_answer1">
Project urls.py file is missing:
if settings.DEBUG:
urlpatterns += patterns(
'',
url(r'^media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT, 'show_indexes': True}),
)
CORRECT CODE:
models.py
from django.db import models
class Lesson(models.Model):
phrase = models.CharField(max_length=200)
progress_bar = models.DecimalField(max_digits=5, decimal_places=2)
lesson_slug = models.SlugField(max_length=50)
def __unicode__(self):
return self.phrase
class Lesson_Options(models.Model):
lesson = models.ForeignKey(Lesson)
option1_photo = models.ImageField(upload_to='images/')
option1_voice = models.FilePathField(path="/media/user123/Elements/Projects/PENCIL/lesson/voice/", recursive=True)
option1_photo_description = models.CharField(max_length=200)
views.py
def detail(request, lesson_id):
le_objects = Lesson.objects.get(pk=lesson_id)
me_options = Lesson_Options.objects.get(pk=lesson_id)
lesson = le_objects.progress_bar
display_test = me_options.option1_photo
return render(request, 'lesson/detail.html', {'lesson': lesson, 'display_test': display_test})
urls.py (Project urls)
from django.conf.urls import patterns, include, url
from django.conf import settings
from django.conf.urls.static import static
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^lesson/', include('lesson.urls')),
url(r'^admin/', include(admin.site.urls)),
)
if settings.DEBUG:
urlpatterns += patterns(
'',
url(r'^media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT, 'show_indexes': True}),
)
urls.py (Application urls)
from django.conf.urls import patterns, url
from django.conf import settings
from django.conf.urls.static import static
from lesson import views
urlpatterns = patterns('',
# ex: /lesson/
url(r'^$', views.index, name='index'),
# ex: /lesson/5/
url(r'^(?P<lesson_id>\d+)/$', views.detail, name='detail'),
# ex: /lesson/5/results/
url(r'^(?P<lesson_id>\d+)/results/$', views.results, name='results'),
)
settings.py
MEDIA_ROOT = '/media/user123/Elements/Projects/PENCIL/lesson/media/'
MEDIA_URL = '/media/'
detail.html
<li class="span4"> <a class="thumbnail"> <img alt="hello"
src="{{ display_test }}" height="300" width="300" class="option1" id="incorrect_answer1"></a> </li>
HTML Output
<img alt="hello" src="images/girl_1.jpg" height="300" width="300" class="option1" id="incorrect_answer1">
This is the documentation for FileField. It seems you've done the first two steps properly. Try to follow step three. Instead of display_test = me_options.option1_photo put:
display_test = me_options.option1_photo.url
or try directly in the template:
<img alt="hello" src="{{ display_test.url }}" height="300" width="300" class="option1" id="incorrect_answer1">