How To Add Django Template Variable In
?
I have a Photo model with two fields: title = models.CharField() path = models.CharField() When I adding the new photo in admin panel, the path is equals to /images/image_ex.jpg T
Solution 1:
You here pass '{{photo.path}}'
as a string to {% static ... %}
, hence it will simply prepend the static URL root to this string.
If you want to use the content of photo.path
, you can use:
<imgsrc="{% static photo.path %}"/>
So {% static ... %}
accepts variables as parameters, and will take the content of the path
attribute of the photo
variable. (of course given that variable is passed, or is a variable you generate with {% for ... %}
loops, etc.
Solution 2:
Uses a for tag
{% for p in photos %}
<imgsrc="{% static '{{ p.path }}' %}"/>
{% endfor %}
Better uses Imagefield as field in your model
In your settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
Create a folder named “media” in your project (at the same level that your apps)
In your urls.py (main)
from . import views, settings
from django.contrib.staticfiles.urlsimportstaticfrom django.contrib.staticfiles.urlsimport staticfiles_urlpatterns
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
In your models.py
Replace the CharField with Imagefield
image = models.ImageField(upload_to="my_folder_name")
Like this:
classPhoto(models.Model):
title = models.CharField()
image = models.ImageField(upload_to="my_folder_name"))
In your views.py
defgallery(request):
photos = Photo.objects.all()
return render(request, 'gallery.html', {'photos': photos})
In your templates
{% for p in photos %}
<imgsrc="{{ p.photo.url }}"/>
{% endfor %}
Solution 3:
Do it like this:
<imgsrc="{static 'images/'%}{{image_ex.png}}">
Use it after the static tag scope ends.
Post a Comment for "How To Add Django Template Variable In
?"