How to passing queryset inside static url in django template? - python

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 }}.

Related

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

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 %}

Build HTML files using Django Template System or Static Site Generator?

I am trying to set up a proper workflow for a personal website.
I am using the Cactus static site generator which makes use of the Django template system.
I know what I want to do, but I am not sure how to do it as the tutorials for Cactus are limited.
This is what my directory structure looks like:
/mysite/pages/
/mysite/templates/
/mysite/mycontent/
/mysite/plugins/
My template, /mysite/pages/menu.html, looks like this:
<p>Welcome to the page!</p>
{% block body %}
{% endblock %}
And one of my page articles, /mysite/pages/testpage.html, looks like this
{% extends "menu.html" %}
{%block body %}
<p> Test Content </p>
{% endblock %}
But what I am trying to do is set this up so that whatever I want to write for Test Content can be written somewhere else and the copied in to the folder. Something like this:
{% extends "menu.html" %}
{%block body %}
{%include "../mysite/mycontent/TestContent.html}
{% endblock %}
Is this something that Django templates needs to manage? Like I said, I am using Cactus which uses Django templates but I have looked around and am not sure what the standard way of doing this is, even though it seems to work with MVC/MVT philosophy.
There is also an option to use Django plugins with Cactus.
Thanks!
I figured out what I was trying to do. I just had to include the html I wanted using the template language.
{% extends "menu.html" %}
{%block body %}
{% include "./file.html" %}
{% endblock %}

Django: Is it possible to call a template from inside another template? [duplicate]

I have a very basic template (basic_template.html), and want to fill in the with data formatted using another partial template. The basic_template.html might contain several things formatted using the partial template.
How should I structure the code in views.py?
The reason I am doing this is that later on the will be filled using Ajax. Am I doing this right?
You can do:
<div class="basic">
{% include "main/includes/subtemplate.html" %}
</div>
where subtemplate.html is another Django template. In this subtemplate.html you can put the HTML that would be obtained with Ajax.
You can also include the template multiple times:
<div class="basic">
{% for item in items %}
{% include "main/includes/subtemplate.html" %}
{% endfor %}
</div>
You can do this using a block. Blocks are a Django Template tag which will override sections of a template you extend. I've included an example below.
basic_template.html
<body>
{% block 'body' %}
{% endblock %}
</body>
template you want to include: (i.e. example.html)
{% extends 'basic_template.html' %}
{% block 'body' %}
/* HTML goes here */
{% endblock %}
views.py:
return render_to_response(template='example.html', context, context_instance)
Doing this will load basic_template.html, but replace everything inside of {% block 'body' %} {% endblock %} in basic_template.html with whatever is contained within {% block 'body' %} {% endblock %}.
You can read more about blocks and template inheritance in the Django Docs
There are mainly 2 ways (2 easy ones)
1:
In base html put
{% include "myapp/sub.html" %}
And just write html code inside your sub.html file
2:
https://docs.djangoproject.com/en/dev/ref/templates/language/#template-inheritance
I just wanted to add differences of extend and include.
Both template and include can use models inserted in current app.
Template is for global usage by your any app. Include is for use in certain apps.
For ex: you want to insert Image Slider to your homepage and about page but nowhere else. You can create Slider app with its own model for convenience and import its model and include in that pages.
If you used template for this example, you would create 2 templates one with slider and everything else other template have.

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

How do I access my own template variables from within a custom template tags template?

I am using Django to build a website.
I have a context processor setup that looks something like this:
TEMPLATE_CONTEXT_PROCESSORS = (
...
"mysite.context_processors.mystandardvariables"
)
This adds some standard variables that I like to use in templates, such as SITE_NAME and SITE_ROOT.
I have just created my first custom template tag and I find that I cannot access these standard variables.
I don't get any errors and my page displays ok, it's just that the variable that I want are not available.
To check which variables are available I already used {% debug %}.
My tag looks like this:
#register.inclusion_tag('search/search_snippet.html', takes_context = True)
def search(context):
form = forms.SearchForm()
return {'form': form }
The template for the tag looks like this:
<form action="{{ SITE_ROOT }}search" method="post">
{% csrf_token %}
<table>
{{ form.as_table }}
</table>
<input type="submit" value="Submit">
</form>
I am including the search tag in my home page like this:
{% extends "base.html" %}
{% load search_tags %}
{% block content %}
{% search %}
{% endblock %}
To answer my own question, I figured out a way to do what I want using a normal template tag rather than an inclusion tag.
#register.tag
def search(parser, token):
return SearchNode()
class SearchNode(template.Node):
def render(self, context):
return render_to_string('search/search_snippet.html',
{ 'form' : forms.FindForm() }, context)
Here I am passing the context through to the function that renders my template to a string.
I would have preferred to implement this as an inclusion tag as it seems like less work, but I wasn't sure how to get it to work.
If anyone knows how to get this working with an inclusion tag please answer and I'll mark your question as the right answer.

Categories

Resources