Displaying an image from string in django template - django

To give you an idea of my starting point:
I have a set of forms with a label and checkbox.
Some of my labels are supposed to display pictures, but not all.
The pictures when they should be displayed are never at the same place with regards to the label text (ie sometimes the picture should be displayed in the middle of the label, sometimes at the beginning, end...).
So the only way I could think of to address this problem was to have in my label at some place, something like
<img src="{{ MEDIA_URL }}/sources/1/2.jpg" height=300px/>
within the text.
The problem is that it is considered as a string and not as an html tag.
Would you have any idea of to address this issue? I'm currently run out of ideas.
Thank you very much.
Soso :)

I managed to make it work. The only thing I needed was to wrap my label containing my former <img> tag with:
mark_safe
imported using
from django.utils.safestring import mark_safe
Thanks!

Related

Django: a custom template tag to convert links inside of a TextField and change the hyperlink text

The scenario is that there are some dynamic texts on some templates, that will contain hyperlinks.
For this, I have a SiteDataKeyValue model, in which the dynamic texts for different parts of the template are inputted. This is the model:
class SiteDataKeyValue(models.Model):
key = models.CharField(
max_length=200, verbose_name="نام متن مورد نظر", unique=True
)
value = models.TextField(verbose_name="متن")
def __str__(self):
return self.key
A solution that I've found already, is Django urlize template tag. As mentioned in the docs, this tag converts texts like https://www.google.com to www.google.com, which is nice but not what I'd like to achieve. I want to be able to change the hyperlink text, so the output would be something like: Click Here!.
I searched for a bit, came across modules like bleach, which is a fine module, but I couldn't find the answer I was looking for (I skimmed through the docs and there was nothing about the hyperlink text).
Also I saw a comment somewhere telling that this could be achieved by writing a custom Django template tag, but although I tried to do this regarding the custom template filters docs, I didn't have a clue to how to achieve this.
I'm not asking for the code, although it would be really appreciated if you provide instructions for writing this custom template tag, or better, if you could point me to something like this that is already out there.
First of all you can extend urlize tag like the answer in this
or you can change the main code which you can find it in django.utils.html and override its url variable to change it.
But I think the best method is extending the urlize tag
like this:
{% text | urlize | change_a_text_filter:{{ dome_new_a_text }} %}
then you can scrape the text and use regex to find >sample-text</a> then you can change it to the argument that defines in your tag
from django import template
register = template.Library()
#register.simple_tag
def change_a_text_filter(format_string, arg):
# find the url that made in urlize with regex
# change it with arg
# return the result
I was on a completely wrong road to solve this problem. I was trying to urlize a link from TextField, but didn't consider the fact that I only needed to implement html code as Visit link.com! in the TextField, and then use safe template tag to render html directly as below:
{{ text.value|safe }}
So in this solution, there is no need to urlize, and of course there is no need to extend this tag neither.
NOTE: As commented by #rahimz (link to comment) I understand that there are safety concerns regarding safe tag, So I should emphasize that only me and a company-trusted admin will have access to admin panel and there is no worries that this admin will send malicious code through this TextField.

OrchardCMS Replacement Tokens for Query Results displaying HTML tags instead rendering them

I am having problems understanding the token system for the output of query / projections.
If I leave the property as is it displays the text content with HTML formatting intact.
But I need to wrap it with a tag, the html tags get displayed as text.
Rewrite Results -> Rewrite output
<div class="collapse" id="toggle_{Content.Id}">
{Content.Fields.CaseStudy.ClientChallenge} </div>
I am trying to create a collapsible text area, I already have a button that hides/unhides the content.
Why is it displaying as text instead of rendering the tags properly.
I think this is because I don't know how replacement tokens work.
Another example problem is up one level on the edit Layout, I want to set the item class to work-item {Category}, Category being the name/title of a property, which I am using for grouping.
Right above the projection: I want to include some html that lists all the Categorys in a ul i.e. data-filter=".experiential" I have tried things like: work-item {Category} and work-item {Content.Fields.CaseStudy.Category}. Category is a "term" (?) from a taxonomy.
I feel like I am failing to understand how it all works.
Submitted as a bug https://github.com/OrchardCMS/Orchard/issues/7355
Will edit and post if it is fixed. In case anoyong else comes across this issue.

New Line on Django admin Text Field

I am trying to create a blog o django where the admin posts blogs from the admin site.
I have given a TextField for the content and now want to give a new line.
I have tried using \n but it doesn't help. The output on the main html page is still the same with \n printing in it. I have also tried the tag and allowed tags=True in my models file. Still the same. All the tags are coming as it is on the html page.
My Django admin form submitted:
The result displayed in my public template:
You should use the template filter linebreaks, that will convert the reals \n (that means the newline in the textarea, not the ones you typed using \ then n) into <br />:
{{ post.content|linebreaks }}
Alternatively, you can use linebreaksbr if you don't want to have the surrounding <p> block of course.
After searching the internet and trying different Django Template Filters, I came across one specific filter, SAFE.
For me, LINEBREAKS filter didn't work, as provided by #Maxime above, but safe did.
Use it like this in your html template file.
{{post.content|safe}}
To have a better understanding of SAFE filter, i suggest reading the documentation.
{{post.content|linebreaks}}
This will make the line in the textbox appear as it is without using \n or \.
{{post.content|linebreaksbr}}
Besides the newline function in your CSS Declaration will work too.

Flask-Images does not work

I'm installed Flask-images for resizing some images. My code are like this:
<img src = '{{url_for('showimages', filename = market.thumbnail, width=100, height=100, mode='crop')}}'>
showimages:
#app.route('/image/user/<filename>')
def showthumbnail(filename):
return send_from_directory(app.config['UPLOAD_FOLDER'], filename)
There are nothing happens and my Chrome devaloper tools said image's url like this:
<img src="/image/user/Untitled-1.png?width=100&height=100&mode=crop">
I know there is another way instead url_for - resized_img_src().
I'm set IMAGES_PATH= os.path.join(APP_ROOT, 'images/').
However this configuration does not work and when I use resized_img_src(), only got broken image icon. I don't have a clue how can fix this.
+Is there any other easy ways to resizing uploaded images?
Your template uses showimages whereas your Flask Python code shows showthumnails, I'll assume this is typo and code actually uses same as template.
Are these really the quote characters you are using in your template? You need to use the single and double quotes or escape the inner single ones. Try this instead:
<img src="{{url_for('showimages', filename=market.thumbnail, width=100, height=100, mode='crop')}}">

What is the right and efficient way of displaying images based on name in Django

I'm really new to Django. I'm having difficulty displaying images based on their name and according to the url pattern.
So basically the url consists of several variables within them and I want to be able to use that to fetch a particular image that is named with those variables.
Example:
localhost:8080/farm/chicken
this would fetch an image inside of my ../static/images/ folder and get:
farm_chicken.jpg
Another example:
localhost:8080/zoo/alligator
would get:
zoo_alligator.jpg
I can fetch the url parameters. So, should I make these image names within my views.py file and pass the names (zoo_alligator) into a context to be retrieved by the template later on? Would this be the correct way?
Thank you for your advice everybody! I appreciate all the help!
You won't actually do something like that, in general. What you should do is to send the image as a context variable from your view function to your template.
If you are using your url node to determine which picture to show, then in your corresponding view function, you are actually using "alligator" or "chicken" to load up the corresponding Animal class.
Once the correct animal object is instantiated, you could send this animal object to your django template and load in the image using a snippet similar to this:-
Like this:-
{% if animal.get_latest_medium_url %}
<img id="animal_image" class="img-rounded left" src="/media/{{ animal_image }}" />
{% endif %}
The get_latest_medium_url is a method in my Merchant class and it computes the url there.
So, should I make these image names within my views.py file and pass
the names (zoo_alligator) into a context to be retrieved by the
template later on? Would this be the correct way?
Sure, this is one way to do it. Something like this:
(r'show/(?P<in_path>.*)$','someapp.image_view')
Then in image_view:
def image_view(request,in_path):
img = in_path.replace('/','_')+'.jpg'
return render(request,'some_template.html',{'path':img})
However, as your view is very simple - you can pass the path directly to the template from urls.py, using direct_to_template:
from django.views.generic.simple import direct_to_template
(r'show/(?P<in_path>.*)$',direct_to_template,{'template':'some_template.html'})
In some_template.html:
<img src="{{ params.in_path }}">
The problem is that you won't get your string formatting done as the default filters do not have a "replace" function. You can easily write a custom filter:
#register.filter
#stringfilter
def format_path(the_path):
return the_path.replace('/','_')+'.jpg'
Then modify the template:
<img src="{{ params.in_path|format_path }}">
You should read the documentation on writing custom filters and tags for more details including where to store the filter code to make sure django can find it.