Django cloudinary image how to add onClick event in template {% %} tag? - django

I am successfully creating a Cloudinary image as follows:
{% cloudinary photo.filename
width='300'
crop='fill'
class='item_photo'
id=photo.filename %}
Which results in html img tag:
<img
class="item_photo"
id="xxxxxx"
width="300"
src="https://res.cloudinary.com/xxx/image/upload/c_fill,w_300/vxxx/xxx.jpg">
However, I want to add an onClick event to the img, but am not able to figure out the correct syntax or perhaps even if it is possible.
I would like html tag to look like:
<img
class="item_photo"
id="xxxxxx"
width="300"
onClick=imageClick('xxxxxx') <=== event variable is same as `id` value
src="https://res.cloudinary.com/xxx/image/upload/c_fill,w_300/vxxx/xxx.jpg">
The id and imageClick variable are themselves populated by Django template tag value photo.filename.
Some things I've tried:
onClick='photoClick(photo.filename)' %}
{% with add:'onClick=photoClick('{{ photo.filename }}|add:') as onclick %}{{ onclick }}{% endwith %}
|add:'onClick=photoClick('{{ photo.filename }}|add:')' %}
How can I construct the onClick=photoClick(xxx) part of this template tag?

You can add the onClick attribute to the img tag as shown below (e.g. photo.filename=sample_image):
{% cloudinary photo.filename width="300" crop="fill" class="item_photo" id=photo.filename onclick="photoClick(this)" %}
Add the script function photoClick(), which can accept the img tag object that can be processed as:
<script type="text/javascript">
function photoClick(img) {
console.log("The src data is: " + img.src);
console.log("The id data is: " + img.id);
var filename = img.src.substring(img.src.lastIndexOf('/')+1);
console.log("The filename is: " + filename);
// Other actions
var src = img.src;
window.open(src);
}
</script>
The resulting HTML tag will be:
<img class="item_photo" id="sample_image" onclick="photoClick(this)" src="https://<your_cloudinary_image_url_path>/sample_image.<ext>" width="300"/>

Related

Ajax: SyntaxError: Unexpected token < in JSON at position 2 [duplicate]

Can I use Django's template tags inside Javascript? Like using {% form.as_p %} in jQuery to dynamically add forms to the page.
Yes, I do it frequently. Your javascript has to be served through django, but if you just have it in the html header as inline javascript you'll be fine.
E.g: I use this to put prefix on a dynamic formset I use.
{% extends "base.html" %}
{% block extrahead %}
<script type="text/javascript">
$(document).ready(function() {
{# Append fields for dynamic formset to work#}
{% for fset, cap, _, tid in study_formsets.fset_cap_tid %}
$(function() {
$('.form_container_{{ tid }}').formset({
prefix: '{{ fset.prefix }}',
formCssClass: '{{ tid }}',
extraClasses: ['myrow1', 'myrow2']
});
});
{% endfor %}
});
</script>
{% endblock %}
Note in "base.html" I have a html head where the jquery libraries are loaded, that contains {% block extrahead %}{% endblock %}.
You can't use Django's template tags from your Javascript code if that's what you mean. All the Django variables and logic stop existing after the template has been rendered and the HttpResponse has been sent to the client. At that moment when Javascript executes, the client (browser) has no notion the variables you rendered the template with (such as "form").
What you can do is have Javascript modify your HTML page using chunks of HTML that were rendered by your Django template.
If you want to generate HTML on client side, I'd recommend to look at client side tempalte libraries (eg. JQuery Templates - use those with the {% verbatim %} templatetag).
If you want to use variables inside your rendered javascript I (that's my opnion), think it's a bad idea. But if all you want is to generate URL for your views, media and static files, I do this a lot.
Take a look to this github: jscssmin
Yes, you can use`
Example : `{{ user.username }}`
Be sure this is not single quotes but '(back tick / back quote)

How do I render all the objects of a child model belonging to a particular object of the parent model on click?

Suppose there are two models Lists and Tasks where 'Lists' have one-to-many relationship with 'Tasks'.
All the objects of the Lists model are rendered on the page like this:
HTML
<div class="grid-container">
{% for list in lists %} <!--lists is context for Lists.objects.all() -->
<div class="grid-item" id="{{ list.id }}" onclick="showTasks( {{ list.id }} )">
{{ list.name }}
</div>
{% endfor %}
</div>
<dialog id="tasks">
</dialog>
JavaScript
<script>
function showTasks(listid){
document.getElementById("tasks").show();
}
</script>
Now I want to render all the tasks_set (all the objects of 'Tasks') related to a particular object of 'Lists' in that dialog with id="tasks".
As it can be seen in the above snippet, I thought of doing it by passing list.id as a parameter to the JavaScript function but couldn't figure out beyond it. How can I achieve it?
Solution 1:
Building on Iain's comment some code. I think it is easiest if you use jQuery so load it in the section of your html template, e.g.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
Then you need a view that returns the required tasks data
def tasks_view(request):
list_id = request.GET.get('listid') # fetch the id of the list
tasks = Lists.objects.get(pk=list_id).tasks.all() # get your tasks
data = {'tasks': render_to_string('tasks.html', {'tasks': tasks})} # pre render the data
return JsonResponse(data)
A remark about the view: You can of course also return the raw Json data. However, in your case I think it is easier to create a small sub-template (tasks.html in the example) and use render_to_string to get the html code you can simply add to your base html page. Don't forget to add the view to your urls.
An example task.html just for the completeness:
<ul>
{% for task in tasks %}
<li>{{ task }}</li>
{% endfor %}
</ul>
Then send an Ajax request to the view (tasks_view) when clicked.
<script>
function showTasks(listid){
$.ajax({
url: '/tasks/', // url of the view created above
data: {
'listid': listid // Your list id
},
data_type: 'html', // as we are receiving a html template
success: function(data){
$('#tasks').append(data.tasks); // append the html code to the dialog
$('#tasks').show();
}
});
}
</script>
Solution 2
In case you do not want to use Ajax and do not mind rendering all your tasks on loading the template you can also create a for the tasks of each list and show them on demand. For this iterate through your lists:
{% for list in lists %}
<dialog id="list-{{ list.id }}">
<ul>
{% for task in list.tasks.all %}
<li>{{ task }}</li>
{% endfor %}
</ul>
</dialog>
{% endfor %}
As you can see you can access the m2m field 'tasks' of each Lists object with list.tasks.all (no ()!). And each has got an individual id.
And then just show and hide the dialogs (just as an example w/o jQuery in case you are reluctant to use it):
<script>
function showTasks(listid){
// Close all dialogs
var all_dialogs = document.getElementsByTagName('dialog');
for (i = 0; i < all_dialogs.length; i++){
all_dialogs[i].removeAttribute('open');
}
// Open the required dialog
var dialog = document.getElementById("list-" + listid);
dialog.setAttribute('open','open');
};
</script>

Displaying image onto django web directly from static directory

Is there a way I can read and display my images from the static directory using bootstrap? eg. display multiple(100) images which I can delete and add new batches with different file name..
I want to avoid doing ,
<div class="thumbnail">
...
<img src={% static '../a.jpg' %}
class="img-responsive"><img src={% static '../b.jpg' %}
class="img-responsive">...
solved!
reference can be found here
Passing a python list to django template &
How to pass a list from a view to template in django
you should get list of image's names to array then using loop for create the image im html Django template.
myList=['img1.png', 'img2.png', 'img3.png']
parse mylist parameter to Django template then using for loop to generate image tag.
{% for img in mylist %}
<img src={% URL::asset('folder_storage/'+img) %} class="img-responsive">
{% endfor %}
It's same method in PHP.

How do you dynamically display images in Django

I'm trying to dynamically display Images in Django. this is my details page
{% extends 'base.html' %}
{% load staticfiles %}
{% block header %}
<!-- Set your background image for this header on the line below. -->
<header class="intro-header" style="background-image: url('{% static 'blog/img/about-bg.jpg' %}')">
<div class="container">
<div class="row">
<div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
<div class="page-heading">
<h1>{{ post.title }}</h1>
<hr class="small">
<span class="subheading">blog detail</span>
</div>
</div>
</div>
</div>
</header>
{% endblock %}
{% block content %}
<h1>{{ post.title }}</h1>
<h4>{{ post.body }}</h4>
{% lorem 5 p random %}
<hr>
<div id="disqus_thread"></div>
<script>
/**
* RECOMMENDED CONFIGURATION VARIABLES: EDIT AND UNCOMMENT THE SECTION BELOW TO INSERT DYNAMIC VALUES FROM YOUR PLATFORM OR CMS.
* LEARN WHY DEFINING THESE VARIABLES IS IMPORTANT: https://disqus.com/admin/universalcode/#configuration-variables
*/
/*
var disqus_config = function () {
this.page.url = PAGE_URL; // Replace PAGE_URL with your page's canonical URL variable
this.page.identifier = PAGE_IDENTIFIER; // Replace PAGE_IDENTIFIER with your page's unique identifier variable
};
*/
(function() { // DON'T EDIT BELOW THIS LINE
var d = document, s = d.createElement('script');
s.src = '//eights.disqus.com/embed.js';
s.setAttribute('data-timestamp', +new Date());
(d.head || d.body).appendChild(s);
})();
</script>
<noscript>Please enable JavaScript to view the
comments powered by Disqus.
</noscript>
<script id="dsq-count-scr" src="//eights.disqus.com/count.js" async></script>
{% endblock %}
So far I tried storing these approaches. I tried storing this in the database
{% static 'blog/img/about-bg.jpg' %}
and called it like this
style="background-image: url('{{ post.title }}')"
that didn't work. Then I tried storing it in the database like this
'blog/img/about-bg.jpg'
and calling it like this
style="background-image: url('{% static '{{ post.title }}' %}')
then I ried storing it like this in the database
static/blog/img/about-bg.jpg
and calling it like this
style="background-image: url('{{ post.title }}')"
I've also tried defining it in the views.py
pic = "path/pic.img"
context = {
"pic": pic
context and calling it
{{pic }}
none of these methods work. It's a little different from Laravel. In laravel
path/{{ post->title }}
would have worked. How can I do this in Django? any and all suggestions are welcome. To be clear I want all my articles to display an image on the index page, then when I click one of them, I am taken to the details page that image for that particular article is displayed
I've figured it out. It's supposed to be stored as
/static/blog/img/about-bg.jpg
not
static/blog/img/about-bg.jpg
the forward slash makes it work. in Laravel this does not matter
From you question I understand that by dynamically you mean that you want to upload an image to your site. So it's not just a static image that is always the same like a logo of your page or something.
You have to do this:
In models.py
from django.contrib.sites.models import Site
def generate_filename(filename): #it adds the image in a folder with the current year
ext = filename.split('.')[-1]
year = datetime.datetime.now().year
return str(year) + '/' + str(int(time())) + '.' + ext
class PageWithImage(models.Model):
image = models.ImageField(upload_to=generate_filename, blank=True, null=True)
site = models.ForeignKey(Site, blank=True, null=True)#this if you want the image linked with your site
Then in setting.py you have to add:
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
MEDIA_ROOT = os.path.join(BASE_DIR, 'img')
MEDIA_URL = '/img/'
Then in the template:
<img itemprop="image" src="http://{{ object.site }}{{ object.image.url }}">
And don't forget to add the image field to admin.py
For adding images dynamically to your webpage using Django :
As we mostly use Jinja for templates,
<img src="{%static 'images/beach.svg' %}" alt="A beach image">
We give this kind of commands to access static image files. But for dynamic, we have to change the 'beach.svg' to something like {{dest2.img}} in the above HTML image tag, if my "views.py" function is like :
def index(request):
dest2 = Destination() // Imported class 'Destination()' from models.py .
dest2.name = 'Beach'
dest2.img = 'beach.svg' // The image name we need.
dest2.desc = 'Some beach description'
dest2.price = 2000
return render(request, 'index.html', {'dest2' : dest2}) // Passing the object value to html page.
If we logically think, the code should be like :
<img src="{%static 'images/{{dest2.img}}' %}" alt="A beach image"> // we cannot do this here!!!
We cannot use a Jinja code inside another Jinja code. So we add :
{% static 'images' as base_url %}
at the top of our HTML page. 'images' is the default folder for images and we are calling it as 'base_url' in this HTML page. So we have to use 'base_url' as path and 'dest2.img' as the file name. so the image source will be like :
<img src="{{base_url}}/{{dest2.img}}" alt="A beach image">
So finally we're done making the dynamic images in Django.!!!😋
First, you cannot use {% static 'blablabla' %} in CSS files.
Second, use this code:
style="background: url(/static/blog/img/about-bg.jpg) no-repeat"
Third, if you will be working with images from models in the future then your code should be:
style="background: url(/{{ your_object.your_img_field }}) no-repeat"

How to render menu with one active item with DRY?

I would like to render a constructions like:
<a href='/home'>Home</a>
<span class='active'>Community</span>
<a href='/about'>About</a>
Where Community is selected menu item. I have menu with same options for several templates but I would not like to create combinations for each template:
<!-- for Home template-->
<span class='active'>Home</span>
<a href='/comminuty'>Community</a>
<a href='/about'>About</a>
...
<!-- for Community template-->
<a href='/home'>Home</a>
<span class='active'>Community</span>
<a href='/about'>About</a>
...
<!-- for About template-->
<a href='/home'>Home</a>
<a href='/community'>Community</a>
<span class='active'>About</span>
We have permanent list of menu items, so, it can be more effective way - to create only one generalized structure of menu then render menu with required option for template.
For example it could be a tag that allows to do that.
Figured out another way to do it, elegant enough thanks to this answer : https://stackoverflow.com/a/17614086/34871
Given an url pattern such as:
url(r'^some-url', "myapp.myview", name='my_view_name'),
my_view_name is available to the template through request ( remember you need to use a RequestContext - which is implicit when using render_to_response )
Then menu items may look like :
<li class="{% if request.resolver_match.url_name == "my_view_name" %}active{% endif %}">Shortcut1</li>
<li class="{% if request.resolver_match.url_name == "my_view_name2" %}active{% endif %}">Shortcut2</li>
etc.
This way, the url can change and it still works if url parameters vary, and you don't need to keep a list of menu items elsewhere.
Using template tag
You can simply use the following template tag:
# path/to/templatetags/mytags.py
import re
from django import template
try:
from django.urls import reverse, NoReverseMatch
except ImportError:
from django.core.urlresolvers import reverse, NoReverseMatch
register = template.Library()
#register.simple_tag(takes_context=True)
def active(context, pattern_or_urlname):
try:
pattern = '^' + reverse(pattern_or_urlname)
except NoReverseMatch:
pattern = pattern_or_urlname
path = context['request'].path
if re.search(pattern, path):
return 'active'
return ''
So, in you your template:
{% load mytags %}
<nav><ul>
<li class="nav-home {% active 'url-name' %}">Home</li>
<li class="nav-blog {% active '^/regex/' %}">Blog</li>
</ul></nav>
Using only HTML & CSS
There is another approach, using only HTML & CSS, that you can use in any framework or static sites.
Considering you have a navigation menu like this one:
<nav><ul>
<li class="nav-home">Home</li>
<li class="nav-blog">Blog</li>
<li class="nav-contact">Contact</li>
</ul></nav>
Create some base templates, one for each session of your site, as for example:
home.html
base_blog.html
base_contact.html
All these templates extending base.html with a block "section", as for example:
...
<body id="{% block section %}section-generic{% endblock %}">
...
Then, taking the base_blog.html as example, you must have the following:
{% extends "base.html" %}
{% block section %}section-blog{% endblock %}
Now it is easy to define the actived menu item using CSS only:
#section-home .nav-home,
#section-blog .nav-blog,
#section-contact .nav-contact { background-color: #ccc; }
I found easy and elegant DRY solution.
It's the snippet:
http://djangosnippets.org/snippets/2421/
**Placed in templates/includes/tabs.html**
<ul class="tab-menu">
<li class="{% if active_tab == 'tab1' %} active{% endif %}">Tab 1</li>
<li class="{% if active_tab == 'tab2' %} active{% endif %}">Tab 2</li>
<li class="{% if active_tab == 'tab3' %} active{% endif %}">Tab 3</li>
</ul>
**Placed in your page template**
{% include "includes/tabs.html" with active_tab='tab1' %}
You could make a context variable links with the name, URL and whether it's an active item:
{% for name, url, active in links %}
{% if active %}
<span class='active'>{{ name }}</span>
{% else %}
<a href='{{ url }}'>{{ name }}</a>
{% endif %}
{% endfor %}
If this menu is present on all pages, you could use a context processor:
def menu_links(request):
links = []
# write code here to construct links
return { 'links': links }
Then, in your settings file, add that function to TEMPLATE_CONTEXT_PROCESSORS as follows: path.to.where.that.function.is.located.menu_links. This means the function menu_links will be called for every template and that means the variable links is available in each template.
I have come up with a way to utilize block tags within menu-containing parent template to achieve something like this.
base.html - the parent template:
Home
About
Contact
{% block content %}{% endblock %}
about.html - template for a specific page:
{% extends "base.html" %}
{% block menu_about_class %}active{% endblock %}
{% block content %}
About page content...
{% endblock %}
As you can see, the thing that varies between different page templates is the name of the block containing active. contact.html would make use of menu_contact_class, and so on.
One benefit of this approach is that you can have multiple subpages with the same active menu item. For example, an about page might have subpages giving information about each team members of a company. It could make sense to have the About menu item stay active for each of these subpages.
Here ist my solution:
{% url 'module:list' as list_url %}
{% url 'module:create' as create_url %}
<ul>
<li>List Page</li>
<li>Creation Page</li>
</ul>
Assuming the nav item is a link with the same URL as the current page, you could just use JavaScript. Here's an annotated method that I use to add a class="active" to a li in a navigation menu with class="nav":
// Get the path name (the part directly after the URL) and append a trailing slash
// For example, 'http://www.example.com/subpage1/sub-subpage/'
// would become '/subpage1/'
var pathName = '/' + window.location.pathname.split('/')[1];
if ( pathName != '/' ) { pathName = pathName + '/'; }
// Form the rest of the URL, so that we now have 'http://www.example.com/subpage1/'
// This returns a top-level nav item
var url = window.location.protocol + '//' +
window.location.host +
pathName;
console.log(url);
// Add an 'active' class to the navigation list item that contains this url
var $links = document.querySelectorAll('.nav a');
$link = Array.prototype.filter.call( $links, function(el) {
return el.href === url;
})[0];
$link.parentNode.className += ' active';
This method means you can simply pop it into your base template once and forget about it. No repetition, and no manual specification of the page URL in each template.
One caveat: this obviously only works if the url found matches a navigation link href. It would additionally be possible to specify a couple of special use cases in the JS, or target a different parent element as needed.
Here's a runnable example (keep in mind, snippets run on StackSnippets):
// Get the path name (the part directly after the URL) and append a trailing slash
// For example, 'http://www.example.com/subpage1/sub-subpage/'
// would become '/subpage1/'
var pathName = '/' + window.location.pathname.split('/')[1];
if ( pathName != '/' ) { pathName = pathName + '/'; }
// Form the rest of the URL, so that we now have 'http://www.example.com/subpage1/'
// This returns a top-level nav item
var url = window.location.protocol + '//' +
window.location.host +
pathName;
console.log(url);
// Add an 'active' class to the navigation list item that contains this url
var $links = document.querySelectorAll('.nav a');
$link = Array.prototype.filter.call( $links, function(el) {
return el.href === url;
})[0];
$link.parentNode.className += ' active';
li {
display: inline-block;
margin: 0 10px;
}
a {
color: black;
text-decoration: none;
}
.active a {
color: red;
}
<ul class="nav">
<li>
Example Link
</li>
<li>
This Snippet
</li>
<li>
Google
</li>
<li>
StackOverflow
</li>
</ul>
I ran into this challenge today with how to dynamically activate a "category" in a sidebar. The categories have slugs which are from the DB.
I solved it by checking to see category slug was in the current path. The slugs are unique (standard practice) so I think this should work without any conflicts.
{% if category.slug in request.path %}active{% endif %}
Full example code of the loop to get the categories and activate the current one.
{% for category in categories %}
<a class="list-group-item {% if category.slug in request.path %}active{% endif %}" href="{% url 'help:category_index' category.slug %}">
<span class="badge">{{ category.article_set.count }}</span>
{{ category.title }}
</a>
{% endfor %}
Based on #vincent's answer, there is an easier way to do this without messing up with django url patterns.
The current request path can be checked against the rendered menu item path, and if they match then this is the active item.
In the following example I use django-mptt to render the menu but one can replace node.path with each menu item path.
<li class="{% if node.path == request.path %}active{% endif %}">
node.title
</li>
I am using an easier and pure CSS solution. It has its limitations, of which I know and can live with, but it avoids clumsy CSS class selectors, like this:
index
Because a space character before active is missing the class selector gets called itemactive instead of item active and this isn't exactly too difficult to get wrong like that.
For me this pure CSS solution works much better:
a.item /* all menu items are of this class */
{
color: black;
text-decoration: none;
}
a.item[href~="{{ request.path }}"] /* just the one which is selected matches */
{
color: red;
text-decoration: underline;
}
Notice: This even works if the URL has additional path components, because then href also matches partially. That could eventually cause 'collisions' with more than one match, but often enough it just works, because on well structured websites a "subdirectory" of an URL usually is a child of the selected menu item.
I personally find the simplest way is to create blocks for each link like so:
# base.py
...
<a href="{% url 'home:index' %}" class={% block tab1_active %}{% endblock %}>
...
<a href="{% url 'home:form' %}" class={% block tab2_active %}{% endblock %}>
...
And then in each relative template declare that link as "active" e.g.:
tab1 template:
{% block tab1_active %}"active"{% endblock %}
tab2 template:
{% block tab2_active %}"active"{% endblock %}
Simply use template tags
# app/templatetags/cores.py
from django import template
from django.shortcuts import reverse
register = template.Library()
#register.simple_tag
def active(request, url, classname):
if request.path == reverse(url):
return classname
return ""
Do like this in your template
{% load cores %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Example</title>
</head>
<body>
<div>
myUrl
</div>
</body>
</html>
Have fun 😎