This is a snippet of my code.
soup=BeautifulSoup(html_document)
tabulka=soup.find("table",width="100%")
dls=tabulka.findAll("dl",{"class":"resultClassify"})
tps=tabulka.findAll("div",{"class":"pageT clearfix"})
return render_to_response('result.html',{'search_key':search_key,'turnpages
':tps,'bookmarks':dls})
I checked the dls, it is a dict contains only one html label
<dl>label contents contains some <dd> labels</dl>
But after pass dls to render_to_response the result is not correct.
The corresponding template code in result.html is:
{% if bookmarks %}
{% for bookmark in bookmarks %}
{{bookmark|safe}}
{% endfor %}
{% else %}
<p>No bookmarks found.</p>
{% endif %}
The output result html contains a python dictionary format like this:
[<dd>some html</dd>,<dd>some html</dd>,<dd>some html</dd>,...]
This appears in the output html. That is very strange. Is this a bug of renfer_to_response?
Well, dls is a python list containing the text of all the matching elements. render_to_response doesn't know what to do with a list, so it just turns it into a string. If you want to insert all the elements as HTML, try joining them into a single piece of text like so:
dls = "".join(dls)
Note that by doing so you are pasting live HTML from some other source into your own page, which is potentially unsafe. (What happens if one of the dds contains malicious Javascript? Do you trust the provider of that HTML?)
You have to use a RequestContext instance when rendering templates in Django.
say like this
return render_to_response('login.html',{'at':at}, context_instance = RequestContext(request))
for this to use, you need to import as follows:
from django.template import RequestContext
Hope this works for you. :)
Related
I was going to create my own friendship view and everything (But I couldn't figure out how to get everything working in a database) So I opted to use something called django-friendship which seems quite good, and It also came with tags to use in the HTML templates but now I am trying to list all the friend requests I can't seem to do a for statement in the tag which is:
{% friend_requests request.user %}
What I would like to be able to do is
{for friend_requests in request.user}
#show this then that#
the link to the github page for the project is this: https://github.com/revsys/django-friendship
If it comes to it I would prefer to create my own friendship implementation, but I don't know where to start.
The friend_requests tag uses a template, which already loops through and creates a list for you:
#register.inclusion_tag('friendship/templatetags/friend_requests.html')
def friend_requests(user):
"""
Inclusion tag to display friend requests
"""
return {'friend_requests': Friend.objects.requests(user)}
source
Here is the template
<ul>
{% for friend_request in friend_requests %}
<li>{{ friend_request }}</li>
{% endfor %}
</ul>
source
To customize it, create a directory friendship and inside it another one called templatetags, and then create a file called friend_requests.html in your app's template directory, and then you can customize the output there.
I have written some code in Python that reads in two strings, removes the punctuation and then compares the words in them within a matrix table which it prints to the console.
How do I convert the code to be utilised within the Django framework. I want to display a similar matrix on the web. I've already imported it into views. Please may someone point me in the right direction? I've been using django project and lynda to learn as I go along,
Edit:
Merci for the help guys. Managed to get it to display on a webpage. But it is printing it all out as a single string. How do I style it a bit better?
Think of passing your data to a "Django webpage" as just passing a dictionary of your values to a Django template from your Django view.
What is a Django template?
A Django template is the 'T' in Django's 'MTV' design pattern. In the conventional MVC design pattern (Model-View-Controller), the View is where you display things. In Django, Templates are where you display things. Oddly enough, the 'View' in Django is actually the Controller. This took me a while to wrap my head around.
Why do we use a dictionary-like context?
By mapping keys to values we achieve super-fast [O(1)/constant] lookup in the Django templates.
With all of this in mind, I'd advocate using 'TemplateView' generic view, doing your work in a utils file, importing utils into views, and then passing your data to the template via the context dictionary. So it would look something like this:
local_utils.py
import string
import pandas as pd
pd.set_option('display.max_columns', None)
def generate_out_matrix():
with open('./arrayattempts/samp.txt', 'r') as file1:
sampInput=file1.read().replace('\n', '')
#print(sampInput)
with open('./arrayattempts/ref.txt', 'r') as file2:
refInput=file2.read().replace('\n', '')
#print(refInput)
sampArray = [word.strip(string.punctuation) for word in sampInput.split()]
refArray = [word.strip(string.punctuation) for word in refInput.split()]
out=pd.DataFrame(index=refArray,columns=sampArray)
for i in range(0, out.shape[0]):
for word in sampArray:
out.ix[i,str(word)] = out.index[i].count(str(word))
return out.as_matrix()
views.py
from appname.local_utils import generate_out_matrix
class Detail(TemplateView):
template_name = 'appname/yourhtml.html'
# Will render on each call to URL for 'Detail'
def get_context_data(self):
out = generate_out_matrix()
context['out'] = out
return context
appname/templates/yourhtml.html
{% if out %}
{% for row in out_matrix %}
{% for o in row %}
{{ o }}
{% endfor %}
<br>
{% endfor %}
{% endif %}
urls.py
path('/your_path', views.Detail.as_view()),
https://docs.djangoproject.com/en/2.0/ref/templates/api/#rendering-a-context
To send your data to your template you should add your variable to context at your views
from django.http import Http404
from django.shortcuts import render
from polls.models import Poll
def detail(request, poll_id):
... // your logic
out // your variable
return render(request, 'yourhtml.html', {'out': out})
In html will be like that
{{ out }}
{% for o in out %}
{{ o }}
{% endfor %}
https://docs.djangoproject.com/en/2.0/topics/http/views/
You can style your table with some CSS or using ny lib struct to handle tables
You can follow this guide
display django-pandas dataframe in a django template
I'n trying to create inclusion tag so I can display data in my navigation bar on every page. The tag will be included in the "base.html" so that way it should display everywhere.
tags.py
#register.inclusion_tag('menu.html')
def show_hoods(HoodList):
gethoods = Hood.objects.all()
return {'gethoods': gethoods}
menu.html
{% for hood in gethoods %}
<h3>{{ hood.name }}</h3>
{% endfor %}
For some reason the menu.html template is blank and is not showing any data.
Also, once I have the menu.html running, will simple {% include 'menu.html' %} work inside the base.html? Will that be automatically rendered?
Edit:
Based on the feedback below, the code above is correct, however the base.html code was incorrect as the inclusion_tag is not loaded with {% include %} but {% load %} is used instead.
corrected base.html
{% load tags %}
{% show_hoods hoodlist %}
Thanks for the feedback!
Directly viewing the menu.html template will not display anything as it has no context variables set. gethoods will be empty so there will be nothing for the for loop in the template to loop over.
One of the main purposes of an include tag is to set extra context variables and then render a template using these variables. Directly viewing the template will show the template without the variables, but including the include template ({$ show_hood %} in your case) will add the context variables (gethoods) and render the template using them.
Answering your second question, you add include templates using their name, (the name of the function by default) rather than the {% include %} tag. The {% include %} tag is for when you simply want to render one template inside of another, and where it either doesn't need any context variables or uses the context variables available to its parent template.
I have a common header used throughout the site. On some pages, based on the URI we're at, I'd like to include/exclude some html content. What would be the proper way to do it? I see a 'url' tag but that obviously isn't it (doesn't seem to work for me at all in fact, on Django 1.5.5). I was hoping for a simple filter, something like:
{% if url == '/dashboard/' %}
<!-- conditional html content -->
{% endif %}
I know that I could pass some custom data from the View action via its context, then check against it in the template, but that feels a bit.. excessive/iffy (?)
You can use request.path in the template to get the current url like so:
{% if request.path == '/dashboard/' %}
<!-- conditional html content -->
{% endif %}
For this to work you must have django.core.context_processors.request listed in your TEMPLATE_CONTEXT_PROCESSORS in your settings.py file.
I have the following code in my template:
{% for req in user.requests_made_set.all %}
{% if not req.is_published %}
{{ req }}
{% endif %}
{% empty %}
No requests
{% endfor %}
If there are some requests but none has the is_published = True then how could I output a message (like "No requests") ?? I'd only like to use Django templates and not do it in my view!
Thanks
Even if this might be possible to achieve in the template, I (and probably many other people) would advise against it. To achieve this, you basically need to find out whether there are any objects in the database matching some criteria. That is certainly not something that belongs into a template.
Templates are intended to be used to define how stuff is displayed. The task you're solving is determining what stuff to display. This definitely belongs in a view and not a template.
If you want to avoid placing it in a view just because you want the information to appear on each page, regardless of the view, consider using a context processor which would add the required information to your template context automatically, or writing a template tag that would solve this for you.