I'm trying to show an img with the Django dynamic url, but I cant get the dynamic url right
url.py
path('Obra/<int:id>/', views.detalle_obra, name="detalle_obra"),
work-single.html
...<img src="{{object.img.url}}"
views.py
def works(request, id):
obj = Work.objects.get(id=id)
context= {
'object':obj
}
return render(request, 'works-single.html',context)
when I render the template this image pop on the console:
Not Found: /Obra/1/static/mySiteWork/img/uploads/Proyecto Obra Cerrillos/P5230031.jpg
I don't know why is showing the "/Obra/1/". When I print {{object.img.url}} it will only show me the "static path static/mySiteWork/img/uploads/Proyecto Obra Cerrillos/P5230031.jpg"
the static files works fine in the rest of templates
Thanks in advance.
This is most likely because of the value of the MEDIA_URL variable from the settings file. The argument upload_to from the forms is relative to the MEDIA_ROOT/MEDIA_URL. Django calculates the path to a user uploaded file as MEDIA_ROOT/MEDIA_URL/file_url.
Seems that MEDIA_URL in your settings is set to "Obra/1".
I solved the problem:
I change this on the html template:
<img src="{{object.img.url}}">
for this:
<img src="/{{object.img.url}}">
Not sure why... but it works fine
Related
Is any thing wrong with this program?
#property
def imageURL(self):
try:
url = self.image.url
except:
url = ''
return url
I used it but django does not render the images uploaded from the admin page
Please anyone with idea on how to fix this issue?
First of all, add django static and media URLS in urls.py (only for DEBUG=True)
Next use src="{{ image_model.image.url }}" in image field
I need to construct the HTML body from a Django view and I cannot find a solution to refer correctly a JPG file ( must say that the HTML is much larger then this, but with other stuff seems that is working for me
):
I've tried this:
from django.template import Template
...
html = Template('<IMG SRC="{% static "base/images/course/website-46-2.jpg" %}">')
return HttpResponse( html )
And I get this error:
Invalid block tag on line 1: 'static'. Did you forget to register or load this tag?
In Django template I resolve this by loading the static files:
{% load static %}
How can I do this in Python ( Django View ) ? Or any other suggestion is much appreciated.
I've tried different solution that I have found on this site and others but none seems to work for me.
Django Version: 2.2.1
You can create an engine with the static library as a built-in. This makes it available to the template without calling {% load static %} first.
from django.template import Template, Context, Engine
engine = Engine(builtins=['django.templatetags.static'])
template = engine.from_string('<IMG SRC="{% static "base/images/course/website-46-2.jpg" %}">')
return HttpResponse(template.render(Context()))
Have you set your STATIC_URL in settings.py? You can do this by the following:
STATIC_URL = '/static/'
Your image would then be found under 'your_app/static/base/images/course/website-46-2.jpg'.
Does the folder structure follow this convention? If not you can set the STATIC_URL to '/base/'
def startchat(request):
template=loader.get_template('app1/chatbot.html')
return HttpResponse(template.render())
This function loads the html page into Django.
Before that , we need to import the module
from django.template import loader
I have a folder which is being populated by images all the time . And I don't know how to make a kind of "loop" which will display all the images in a browser using Django
You definitely should have provided some code, but anyway here’s a quick way I think should solve your problem.
I am guessing the image folder is tucked away somewhere in the media folder and already linked in the settings.py file. So simply do these in the views.py and the Django template and you should be good.
Views.py
def gallery_view(request):
path = settings.MEDIA_ROOT
img_list = os.listdir(path + "(path to image folder in media)")
context = {"images": img_list}
return render (request, '(path to django template)', context)
Template
{% for image in images %}
<img src="{{MEDIA_URL}}path to image folder{{image}}">
{% endfor %}
it depends on what the usage. you can use file methods like open() and read the image data, taking a relative path of the folder with respect to your BASE_DIR. Or if the images are static file, you just need to add a STATIC_URL and get them from your template using template tags.
However, you should give us some code, it will help us know your problem
I know that derivatives of this question have already been asked. But those questions are outdated and I would like to hear some new answers for new versions.
I have a model and it has a file field in it.
class MyModel(models.Model):
field = models.FileField()
I can upload files with this model by using the admin panel of django and I can set its location with the MEDIA_ROOT settings variable. But I can't download this file in the view. I have tried given its URL but I usually get the "404 not found" error.
def download(request):
file = # code to get the the model instance.
context = {'file': file}
return render(request, template, context)
Here is the code in template:
Download Link
This throws a 404 error. I know why it throw this error. Because no url deffinitions exist for that url.
So, how can I download this file?
Django 1.8.7, Python 3.4.3, ubuntu 14.04
In development, you can do this to get MEDIA_URL active
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)
I'm writing a view that displays a set of images on a page.
This is the model
#models.py
class Movie(models.Model):
title = models.CharField(max_length = 500)
poster = models.ImageField(upload_to = 'qanda/static/movie_posters')
#index.html
<img src = "{{ STATIC_URL }}movie_posters/{{ movie.poster }}"></a>
When I runserver, the image doesn't appear. The URL the image is trying to load is
http://127.0.0.1:8000/static/movie_posters/qanda/static/movie_posters/image.jpg
When the URL it should be trying to load is
http://127.0.0.1:8000/static/movie_posters/image.jpg
My assumption is that since movie.poster is located at 'qanda/static/movie_posters', when I render it on HTML, it is loading the Static URL (127.0.0:8000/static) and then the location 'qanda/static/movie_posters' at the end. How do I make the image render correctly?
There are two pieces of how image url is calculated.
First in your settings.py you define MEDIA_ROOT. MEDIA_ROOT specifies an absolute folder on your computer where media will be stored. So for example for these settings:
MEDIA_ROOT = '/abs/path/to/media/'
and if you have a field
models.ImageField(upload_to='movie_posters')
then images will be stored at:
/abs/path/to/media/movie_posters/
/abs/path/to/media/movie_posters/poster.jpg <- example
This deals with where media is stored on your hard drive.
Second piece is how to calculate urls for these media files. For that you define MEDIA_URL in your settings.py. That essentially maps a URL to your MEDIA_ROOT location. So then if your MEDIA_URL is:
MEDIA_URL = 'http://localhost/media/'
Then if you want to access an image stored at movie_posters/poster.jpg which has an absolute path of /abs/path/to/media/movie_posters/poster.jpg, its URL should be http://localhost/media/movie_posters/poster.jpg. You can compute the URL by doing:
{{ MEDIA_URL }}{{ movie.poster }}
Please note that I am using MEDIA_URL instead of STATIC_URL. Those are not the same thing. Computing urls like that however is not very neat. Thats why Django's ImageField and FileField have an url attribute:
{{ movie.poster.url }}
Django will then compute the proper url depending on your MEDIA_URL setting.
Note:
For all of this to work, you have to have a separate media server running. Django does not serve any media files. In development it is only capable of serving static file (not same as media files). So in development one nice trick to serve media files is to use Python's simple web server. For that, open a new terminal (on Linux and Mac) or Command Prompt (on Windows) window/tab and navigate to your media folder. Then just execute the following command there:
python -m SimpleHTTPServer 8090
and make sure your setting is:
MEDIA_URL = 'http://localhost:8090/'
and then Python will serve your media files. That works nice for development.
If you want to serve your media just using the development server you can add this for the time being to your urls.py
urlpatterns = patterns( ...all your awesome urls...) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
you can define a custom template tag which returns the basename of the URL like this:
from django import template
import os
register = template.Library()
#register.filter
def getBasename(myURL):
return os.path.basename(myURL)
this should go in your custom template tags (eg. customTemplateTags.py) file within your templatetags directory of your app.
Then you can use the filter in order to get only the image filename, not the entire URL.
{% load customTemplateTags %}
<img src = "{{ STATIC_URL }}movie_posters/{{ movie.poster.url|getBasename }}"></a>