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
Related
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
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 have several hundred static html pages, with an index html page, that I need to bring into Django. I can't figure out the easiest way to do that, I know I'm missing something simple. Any advice?
Nothing fancy needed, just need to dump them in a directory and allow users to navigate to them.
You need to create a view and a url for each html template, iI'm going to put you a simple example here but it's highly recommended that you read Django's documentation or a tutorial :
First, you create a view in a views.py file :
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.views.generic import View
class LoadTemplateView(View):
template_name = ['thenameofyourdjangoapp/yourtemplatename.html']
#You put any code you may need here
def get(self, request, *args, **kwargs):
return render(request, self.template_name)
Then, you must create a url that reads that view in a urls.py file :
from django.conf.urls import patterns, url
#Here you import from views the view you created
from .views import LoadTemplateView
urlpatterns = patterns(
url(r'^myurl/$', LoadTemplateView.as_view(), name="load_template"),
)
Last, in your let's say home html template, you assign this url to a submit button in order to call it by the name you gave it on urls.py (load_template in this case) :
<html>
<body>
<div>
<a class="option-admin" id="id_go" href ="{% url 'yourdjangoappname:load_template' %}"> Go to template </a>
</body>
</html>
</div>
As I said anyway, it's better that you read the complete Django documentation as well:
https://docs.djangoproject.com/en/1.9/
If these are legacy static pages that you do not plan to touch again, then I'd leave django out of it. I'd put them all in a directory or subdomain and serve them directly from the server (probably nginx, maybe apache, whatever you're using). As a general rule, you don't want Django serving static assets, you want the proxy server serving them.
You COULD move them into Django and manage them like other Django static assets, as described in the Managing Static Files Documentation, but if they're already out there, then there's not a whole lot of advantage over just serving them as outlined above.
And finally, if you wish to fully integrate them into your Django site, then you should probably start with the template documentation.
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)