Django: Is there a way to use static with default_if_none? - python

In my Django template I'm using static to pull images from the static/ folder based on each item's (byte) id property. An example of a path to an image would be: static/images/promo-abc.png I'm building the path to the image using with:
{% for byte in bytes %}
{% with 'images/'|add:'promo-'|add:byte.id|add:'.png' as image_static %}
<img class="promo-image" src="{% static image_static %}"/>
{% endwith %}
However if there is no image based on the item's id I'd like the 'default' image to be used: static/images/promo-dummy.png. For that I'm trying to use default_if_none but so far this isn't working (getting error: Could not parse some characters:...)
{% with 'images/'|add:'promo-'|add:byte.id|add:'.png' as image_static %}
<img class="promo-image" src="{{% static image_static |default_if_none:'images/promo-dummy.png' %}}"/>
{% endwith %}

Related

How to passing queryset inside static url in django template?

So, I have image in static folder, with the name of image same with username field that I have created. I want to show the photo for every posting based on the post that made by that user. I just thinking to pass the queryset inside static url like this:
{% for post in data %}
<img src="{% static 'project/image/{{ post.username }}.jpg' %}" alt="Profile" id="profile_image">
{% endfor %}
But my image don't want to show up (error), and the terminal looks like this:
[27/Feb/2021 15:43:14] "GET /static/project/image/%7B%7B%20post.username%20%7D%7D.jpg HTTP/1.1" 404 1758
Is there any way to do this?
If you want to use the curly brackets, then you need to hard code the whole path of the image.
static/project/image/{{ post.username }}.jpg
It uses {{ post.username }} as text, and then percentage encodes it. In order to interpret it, just remove the curly brackets and work with the |add: template filter [Django-doc]:
{% with post.username|add:".png" as username %}
<img src="{% static 'project/image/'|add:username %}" alt="Profile" id="profile_image">
{% endwith %}
For example:
>>> Template('{% load static %}{% with post.username|add:".png" as username %}{% static "project/image/"|add:username %}{% endwith %}').render(Context({'post': {'username': 'foo'}}))
'/static/project/image/foo.png'
That being said, this is quite complicated. If you work with a FileField [Django-doc], then you can convert this to media URLs, and render this with {{ myobject.myfilefield.url }}.

How can you display either a video or image file in a Django Template depending on what type the uploaded file is?

I am trying to display a file from a foreign key set of a model instance. The file can either be videos or pictures and is uploaded by users (think similar to Instagram). How can I display the file as <video> or <img> properly depending on the file type that was uploaded?
I am currently using <video> or <img> tags in html to show the file and they both work but only if the file is of the appropriate type. If the file is of the other type the incorrect tag will show a black box on the site.
{% if result.resultfile_set.all %}
{% for resultfile in result.resultfile_set.all %}
<video controls>
<source src="{{ resultfile.file.url }}">
</video>
<img src="{{ resultfile.file.url }}" />
<p>Caption: {{ resultfile.caption }}</p>
{% endfor %}
{% endif %}
Expected results are that if the file that has been uploaded by the user is a video file, display it as such; or if the file is an image file, display it as image. Instead I am currently only able to display both file types every time where one of them displays properly and the other displays as a black box
I would suggest checking the mime type (link.
Supposed you have a model called Media:
class Media(models.Model):
media = models.BinaryField(...)
def generate_html(self):
if mime_type(self.media) == "image":
return <img></img>
elif mime_type(self.media) == "video":
return <video></video>
else:
raise Exception("media type not understood")
Now you can use the generate_html method in your template
You can send type of media along with url and use conditional rendering to display appropriate media
{% if result.resultfile_set.all %}
{% for resultfile in result.resultfile_set.all %}
{% if resultfile.file.type == "video" %}
<video controls> <source src="{{ resultfile.file.url }}"> </video>
{% elif resultfile.file.type == "image"}
<img src="{{ resultfile.file.url }}" />
{% else %}
<div> Unsupported Media Format </div>
{% endif %}
<p>Caption: {{ resultfile.caption }}</p>
{% endfor %}
{% endif %}
Your result.resultfile_set.all will look something like
[{
file: {
type: "image",
url: "example.com/foo.png"
},
caption : "foo"
},
{
file: {
type: "video",
url: "example.com/bar.mp4"
},
caption : "bar"
}]
Don't worry, How can you display either a video or image file in a Django Template, I have answer for that
Use below code
{% for msg in post_user %}
{% if msg.p_image_path.url|slice:"-4:" == ".mp4" %}
#use video tag
{% else %}
#use image tag
{% endif %}
{% endfor %}
I tried a lot of methods finally the best solution is this:
models:
from mimetypes import guess_type
class Post(models.Model):
media = models.FileField()
def media_type_html(self):
"""
guess_type returns a tuple like (type, encoding) and we want to access
the type of media file in first index of tuple
"""
type_tuple = guess_type(self.media.url, strict=True)
if (type_tuple[0]).__contains__("image"):
return "image"
elif (type_tuple[0]).__contains__("video"):
return "video"
in templates you can access the type like this:
{% if post.media_type_html == "image" %}
<img src="{{ post.media.url }}">
{% elif post.media_type_html == "video" %}
<video controls>
<source src="{{ post.media.url }}">
</video>
{% endif %}

Could not parse the remainder: '(object.listattribute)' from 'len(object.listattribute)'

I have a model with a list attribute
class myObj:
def getlist(self):
return self.list
The list is populated with objects or instanced as an empty list.
In a template I perform the following:
{% if len(myObj.list) > 0 %}
<img class="status" src="{% static "images/Check.png" %}" />
{% else %}
<img class="status" src="{% static "images/YellowWarning.png" %}" />
{% endif %}
I am receiving the following:
Could not parse the remainder: '(myObj.list)' from 'len(myObj.list)'
What am I doing wrong?
len(myObj.list) is invalid syntax in django templates.
You could use the length filter instead.
{% if myObj.list|length > 0 %}

Django Server Static files

I am trying to use the following code to link to the correct image based on the rating. However the server interprets as http://127.0.0.1:8000/static/images/rating-%7B%7Bfeedback.reception_courtesy%7D%7D.gif instead of http://127.0.0.1:8000/static/images/rating-1.gif
<img src="{% static 'images/rating-{{feedback.reception_courtesy}}.gif' %}" alt="My image"/>
I am not sure where I am running wrong here.
The problem is that variables are not interpolated within the url parameter of {% static 'url' %}, so {{feedback.reception_courtesy}} is taken literally.
Do it like this:
<img src="{% static 'images' %}/rating-{{feedback.reception_courtesy}}.gif" alt="My image"/>
This works fine because the variable is now outside of {% static ... %}, and because {% static 'one/two/three' %} is equivalent to {% static 'one/two' %}/three

load static file with variable name in django

I'm trying to do load the following static file
img file
where image is in a for loop of images derived from a database.
But I simply got an error Could not parse the remainder: '{{' from ''static/matrices/'{{'
What should I do to fix this? I can't use relative paths because this will be used by subsections as well, with the same html template.
You should pass a full string to the static tag from staticfiles. This is so it can use your staticstorages to find your file.
{% load staticfiles %}
{% with 'images/'|add:image.title|add:'.png' as image_static %}
{% static image_static %}
{% endwith %}
But in your use case it might be better if you just store the path of the images on the image model itself.
I got this to work by using an empty string for the static path and then using my variables in their own section, like this:
<a href= "{% static "" %}{{obj.a}}/{{obj.b}}/{{obj.c}}.gz" >Name</a>
You can use get_static_prefix template tag. get_static_prefix is a variable that contains the path specified in your STATIC_URL. Your code would be:
{% load static %}
img file
or
{% load static %}
{% get_static_prefix as STATIC_PREFIX %}
img file
Reference: get_static_prefix
You should avoid nesting tags.
What are you trying to solve? Isn't the image part of dynamic content? The static tag is for static content not uploaded media files.
If you must use the static tag the correct way would be something in the order of;
{% static image %} or {% static image.file %}
Depending on the object layout. If you're using an ImageField (inherits FileField) the image object already holds the path, so there's no need to manually add extensions.
What I ended up doing was to just split the path from the name itself. Those images represents tabs, are static and in a sequence. They are not connected to the database imagewise.
I didnĀ“t want to repeat the html for every run so I ended up doing a forloop like this, a bit simplified.
{% for option in options_obj %}
<img class="highlight" src="{% static "store/img/editor/tab-" %}
{{ option.name.lower }}-selected.png">
{% endfor %}
EDIT:
Even though this does work in most situations it can really mess stuff up as well. For me this occured when having different images for different language settings and at the same time using tools like CachedStaticFilesStorage. If you need to add language code or something else to your image this is a more solid solution
{% for option in options_obj %}
<img class="highlight" src="{% static "store/img/editor/tab-"
|add:LANGUAGE_CODE|add:"-selected.png" %}">
{% endfor %}
Too many quotes!
Just
img file
and you don't have to call the static in the link because you already load the static

Categories

Resources