Django - How to make anchors change HTML list - python

I have the following snippet of HTML:
On my django webpage, i get a list that looks as follows:
Each "Part" anchor corresponds with a Part object in Python. Now, I'd like to make it so that when the user clicks on "Part_2", the datapoints of that Part are shown just below it.
On the image, the datapoints of the first part are shown within the nested list. I hard coded this. I looked into calling a python function with an argument from the template, but that is not possible.
What would be an easy way to make this happen?

You can achieve this on the client side. First, create a detail element in your HTML and put a summary and the tags that you need (in this case, I'll be using a <p></p>) as childs:
<details>
<summary>Part 1</summary>
<p>Epcot is a theme park at Walt Disney World Resort featuring exciting attractions, international pavilions, award-winning fireworks and seasonal special events.</p>
</details>
What's inside the summary tag will represents the title and below that goes the hidden text that can be accessed by clicking in the arrow on the side of the title.
Then, make sure you filter in your function in views.py the parts by part_1 and part_2 and then pass them into your context. Lastly, render the items like this:
<details>
<summary>Part 1</summary>
{% for part in part_1 %}
<p> {{ part.tag }}</p>
{% endfor %}
</details>

Related

Sending and rendering HTML syntax via jinja variable

I need some complicated operations to render some dynamic trees in my front-end. But as I can't find any way to run recursion in my jinja or front-end, I take an approach to make a string in my views.py along with HTML syntax and render them in the front-end to get the desired output something like this (As an example, here I skip the original complicated string because there is no need for it):
in views.py:
test = "<h2>Hi This is from django</h2><ol><li>abc</li><li>mno</li><li>xyz</li></ol>"
mydict={
'test' : test,
}
return render(request, 'app\index.html', mydict)
In index.html:
<div class="container-fluid">
{{ test }}
</div>
My desired output with this code is:
Hi This is from
djangoabcmnoxyz
But the obtain output is:
<h2>Hi This is from django</h2><ol><li>abc</li><li>mno</li><li>xyz</li></ol>
Please suggest to me, is there any way to render the jinja string variable along with the effect of HTML in my front-end? If not then how can I take an approach to render any tree dynamically in my front-end where the level, leaf node, intermediate node, etc all info come from the database.
You can use the django-template-filter safe for this.
{{ test | safe }}

How to set values passed from python list to a html progress bar

I have an application where people can read news items and comment.Then those comments are analysed using NLP techniques and comments are classified in to two categories as positive, negative. What I want to do is display how much percentage of comments are positive and how much percentage of comments are negative under each news item.So what I did was I added the [id, headline, newsText, date , positiveCommentPercentage, negativeCommentPercentage] data of each news item in to a Python list and appended it in to a another List and passed it to the web page.
list = [id, headline, newsText, date ,positiveCommentPercentage ,negativeCommentPercentage ]
newsData.append(list)
template = 'AppOne/news.html'
return render(request, template, {'nd': newsData})
I could successfully display the news headline,news and date on the web page as follows,
<div>
{% for x in nd %}
<h2>{{x.1}}</h2>
<h5>{{x.2}}</h5>
<h6>{{x.3}}</h6>
{% endfor %}
</div>
But I want to show the number of "positive comments percentage" and "number of negative comments percentage" under each news item as 2 progress bars as shown in the image
So I tried to use the html progress bars shown in 'w3schools' site.
<div class="w3-light-grey w3-round">
<div class="w3-container w3-blue w3-round" style="width:60%">60%</div>
The question I have is how to set the positiveCommentPercentage ,negativeCommentPercentage values passed from python list, to the style width attribute of the div.
I'm using Django framework here.So please help me to do that or suggest a new way to that using any easy way.
I have never encountered that interpolation style. I am going to look it up... But if it works for the headline, text and date, am sure it would work for the sentiment percentage too. For positive comment, inside your loop, something like:
<div class="w3-container w3-blue w3-round" style="width:{{x.4}}%">{{x.4}}%</div>

Mouse Over in a django template

I have a CSS element thats been declared something like :
span.green_box {width:5px, height:7px ....and other specifications.}
I really dont know any CSS and its not my code. However I do understand that what it does is that it is creating a green coloured box of the given dimensions.
Now in my Django-template I want to display a text on mouseover on this green_box. Just displaying a text would not have been a problem because its done something like this in my django template :
<span class="green_box" title="I am green."></span>
And this works. But I have to refactor it to display something like I am Green and today is 28-6-2013
So for this I have a custom tag, get_todays_date that returns the current date as a string.
And I want to do something like,
<span class="green_box" onmouseover="I am Green and today is %s" % {{get_todays_date}}></span>
My intention is to reproduce the value returned by get_todays_date into %s. I wrote it to describe the structure. This obviously doesn't work. I've looked over on other similar questions but their solution don't work. Most are for mouse over on an image, and a predefined text. So how can I display the text including the value returned by get_todays_date on mouseover on the green_box?
There is no string formatting in django templates as there is in python. There is also a template tag which is able to retrieve todays date (https://docs.djangoproject.com/en/dev/ref/templates/builtins/#now). Hope this leads into the right direction.
You could try something like this:
<span class="green_box" onmouseover="I am Green and today is {% now "d-n-Y" %}">

if condition in template to display link in django

In my django app's index.html (which I consider as the home page of the site)I am giving links to various locations in the website.When the user reaches one of the locations,he should find a link there, to get back to the home page.So I created a base.html to be inherited by all the pages including index.html.In the base.html,I am providing these links.
base.html
...
Archives
<br/>
Reports
<br/>
Home
<br/>
..
My problem is that ,when I am on index page(home) ,I don't want to display the home link.Is this possible to do so in the template,using an {% if %} condition?
Currently I am not passing any parameter in the view
#login_required
def index(request, template_name):
print 'index()::template=',template_name
return custom_render(request, {},template_name )
def custom_render(request,context,template):
req_context=RequestContext(request,context)
return render_to_response(template,req_context)
Firstly, you can use the django render shortcut to avoid having to use the long-winded custom_render.
from django.shortcuts import render
#login_required
def index(request, template_name):
return render(request, template_name,extra={})
You can be cheeky and in your base.html do something like:
{% url home as home_url %}
{% if request.path != home_url %}Home{% endif %}
to quickly check if the current page is the home page.
If it might get more complicated in the future, you can use a template tag to check whether or not the current URL you are on matches another URL. Here is a template tag I have used before to check if a menu link is currently active:
https://gist.github.com/2049936
This isn't exactly what you asked for, but an alteratively way to do this which I often much prefer is to use JavaScript to either hide or change the color of links to the current page. For example, if you were using jQuery:
// Assumes relative paths in a elements
$('a[href="' + window.location.pathname + '"]').each(function (index, element) {
$(element).addClass('someClass');
});
someClass could be a CSS rule to set the 'display' attribute of that element to 'none', or to simply make the link look like plain text, and behave like plain text when mousing over or clicking on it.
This has two possible advantages:
it prevents your template from becoming too convoluted, and from being difficult to maintain if you start arbitrarily adding nav elements
you have the ability to keep your nav consistent between pages, which in my opinion is a good design decision
It's no silver bullet, but I think it's important to recognise that sometimes these things aren't necessarily best done in templates. I think of my django templates first and foremost as a way of structuring data. There will always be some element of presentation in them, but I try to remove that as much as possible. Others will disagree.

Django Images Display

Ok, now I know how to display images on ONE /myurl/ in Django as a list (YEAH!)
But how can I display ONE Image per url with a button to click to the next image etc.
So basically I would want to come to the first /urlstart/:
text and a next button.
brings user to e.g. /urlstart/1
There the first image of a List is displayed and below that a button.
That brings user to /urlstart/2
Here the next image of a list is displayed.
etc.
How does the url.py regex part have to look like so this is possible?
How does the view has to be tweaked to get 1 List of Images but multiple urls?
And finally if anybody has implemented this with a down loadable and installable module/library, like e.g. photologue (which unfortunately did not work for me) or any better idea than that I would be really happy to get some insights on how to make this fast and efficient.
Thanks so much to everybody who takes the time to answer!
URL regex could look something like this:
url(r'^urlstart/(?P<image_id>\d*)/?$', 'urlstart', name='urlstart')
View code could look something like this:
def urlstart(request, image_id=0):
if image_id == 0:
image = None
else:
image = get_object_or_404(Image, image_id)
next_image = image_id + 1
return render_to_response('template.html', locals(), context_instance=RequestContext(request)
Template code:
{% if image %}
<img src={{ image.url }}>
Next
{% else %}
Put your text here. See first image by clicking here
{% endif %}
Obviously this is simplified. For example, you may want to check to see if there is an image to come next.
Hope this helps.
Take a look at Pagination which will provide you with Next/Previous links, etc.
Also, it would probably be a good idea to use permalinks and pass the next/previous image in from the view instead of hard-coding the URL into the template.

Categories