Django and wrap lines problem - python

I've a problem from many years.
The problem is a long text not separated by white spaces in a div. No wrap is applied and it breaks all layout.
How can I fix in django in a good way?
This is what I see:

As I understand the question it is HTML-side problem, not django-side. For HTML solution look How to word wrap text in HTML?. If you still want to wrap text in python code, textwrap.wrap will help you.
Also there is convenient template tag for this: wordwrap. It uses django.utils.text.wrap function which seems more suitable for using in Django projects.

This was bugging me as the built-in word-wrap template tag should have just worked. Instead use this...
{{ value|wordwrap:50|linebreaksbr }}
or
{{ value|wordwrap:50|linebreaks }}
depending if you want <br> or <br> and <p> tags

I don't know if it helps, but an approach could be creating a new filter based on truncatewords filter.
https://docs.djangoproject.com/en/dev/ref/templates/builtins/#truncatewords
Code looks very simple:
def truncate_filter(value, maxlen):
if len(value) <= maxlen:
return value
return value[:maxlen-2] + '..'
Another ideia is using: {{ username|stringformat:".10s" }} to truncate in 10 characters.
https://docs.djangoproject.com/en/dev/ref/templates/builtins/#stringformat

Related

Hubspot - filter to convert text to slug format using HubL

I am developing a template for a client in Hubspot's COS and I am struggling to find a HubL filter that will convert a text/string into a slug format.
For example, I want to be able to convert This Text into this-text. My goal is to use this feature to dynamically assign a css class based on a module text field.
I am looking for an equivalent feature to WordPress' sanitize_title() function.
HubL is based on Python. I am not sure what native Python features work in HubL, but I would be open to that approach as well.
If anyone has accomplished this and has some insight it would be much appreciated.
Thanks!
{% set var = "This Text" %}
{{ var|lower|replace(' ','-') }}
There's a space between the quotation marks in replace's first argument.

Django / Python make newline with '\n'

I'm quite new to using Django, so please be gentle, if this is a stupid question.
I'm trying to play with some stock-information in Python/Django. I'm getting the stock-rates from Yahoo Finance (with urllib). Whenever I get some stock-information, then I will get it like this (yep, it's one long string):
[b'Date,Open,High,Low,Close,Volume,Adj Close\n2014-12-01,26.16,26.22,25.85,26.02,48967100,25.54\n2014-11-28,26.80,26.90,26.44,26.49,31185200,26.00\n2014-11-26,26.89,26.97,26.78,26.87,19289700,26.38\n2014-11-25,27.01,27.03,26.84,26.86,28028000,26.37\n']
I then send it to a template with Django, using
to_be_returned = RequestContext(request, [[DICTIONARY_WITH_VARIABLE]])
and then
return HttpResponse(template.render(to_be_returned)
Is there a way, to get Django to beautify the long string for me? So I don't have to manipulate the string and replace all \n with <br />, in order for me to be able to read it easier? And what does the [b' ... '] mean (that contains the entire result?
Thanks for your assistance.
Use the linebreaksbr template filter:
{{ my_string_with_n|linebreaksbr }}
b'...' is a python3 byte string literal.
You do not attached a template.
Wrap out tag with
<pre></pre>
You can add html tag to the strings that you write in the response
For example :
response2.write('</br></br>List of Courses : ')

Jinja 2 safe keyword

I have a little problem understanding what an expression like {{ something.render() | safe }} does .
From what I have seen, without the safe keyword it outputs the entire html document, not just the true content.
What I would like to know, is what it actually does, how it functions .
The safe filter explicitly marks a string as "safe", i.e., it should not be automatically-escaped if auto-escaping is enabled.
The documentation on this filter is here.
See the section on manual escaping to see which characters qualify for escaping.
Normally text is HTML-escaped (so <b> would be written out as <b>, which would render as <b>).
When you put |safe after something, you're telling the template engine that you have already escaped the text yourself, i.e. "it's safe to render this directly". So it will not do that encoding for you.
For more information: http://jinja.pocoo.org/docs/templates/#html-escaping
For anyone coming here looking to use the safe filter programmatically: wrap it in a markupsafe.Markup class, on which Jinja2 depends on.
Expanding on #data's answer, here's an example of using markupsafe.Markup:
import markupsafe
vals = {}
vals["name"] = markupsafe.Markup("<b>Duck</b>, Donald")
html = template.render(vals)
The resulting HTML will show Donald's last name in bold wherever the template contains {{name}}.
You can go this way
post.body is the variable that is getting the data from the database or any file.
{{ post.body | safe }}
I hope you will get it.

two or more dots in a django template after the variable

In a django template, is it possible to have two (or more) dots after a variable? For example, say I have a list of objects that I first want to use a list-index lookup for and then once I have the object, I want to call its method for getting the absolute url, should that work?
For example:
{% for entry in myList %}
{{ entry.0.get_absolute_url }}
{% endfor %}
So the 0 is asking for the first item in the list which is an object, then I want to get the absolute url. It doesn't work when I try it but it doesn't return an error either. Is there a better way to accomplish what I'm trying to do?
To clarify it, what's strange is that:
This works:
{{ singleObject.get_absolute_url }}
In that case if I just try {{ singleObject }}, I get the unicode value of that object so something like: John Smith
This doesn't work:
{% for object in objectList %}
{{ object.get_absolute_url }}
{% endfor %}
But in this case, if I put in {{ object }}, I no longer get the unicode value. I get: [<Name: John Smith>] (name being the name of the model)
Basically, the method works when it's outside of a loop. Could there be any reason for that?
more than one dot absolutely works.
based on your comment, there is no entry.0 because entry IS the first item in the list cause you are already looping through `myList'
just use entry.get_absolute_url instead
but if you only want to print out the url for the first entry, forgo the for loop and just use myList.0.get_absolute_url
UPDATE:
there's a tip from 'the pragmatic programmer' that says:
``select’’ Isn’t Broken
It is rare to find a bug in the OS or the
compiler, or even a third-party product or library. The bug is most
likely in the application.
i think you assumed that django templates were behaving weird, when the truth is you were not building your list correctly. don't be afraid to show some of your actual code, by abstracting the problem for us, you removed the part that included the problem
I got it. I had brackets around each item in my list like so:
objectList = [['John Smith'], ['Jim Jones'], ['Bill White']]
Silly me! Thanks so much for your all your input
What you are doing is perfectly acceptable in Django templates. There is no better way to accomplish what you're trying to do.

Google appengine string replacement in template file

I'm using google appengine (python, of course :) ) and I'd like to do a string.replace on a string from the template file.
{% for item in items %}
<p>{{ item.code.replace( '_', ' ' ) }}</p>
{% endfor %}
But that isn't working. So we cannot execute anything other than basic checks in the app engine templates. Is that Correct ?
Another related problem is I'm trying to shorten a string and make it available to the template.
Each furniture object has a name and a longer description field. In this view I'm rendering, I want only the first 50 characters of the description field.
So I tried something like
items = db.GqlQuery( 'select * from furniture' )
# edit: if you change the above line to
# items = db.GqlQuery( 'select * from furniture' ).fetch( 1000 )
# the .fetch() command makes the addition of dynamic properties work!
for item in items :
item.shortdescr = item.description[ 0:50 ]
# pass data off to template for rendering
self.response.out.write(
template.render( 'furnitureAll.html', { 'items' : items } )
)
Template goes
{% for item in items %}
<p>{{ item.name }}</p>
<p>{{ item.shortdescr }}</p>
<!-- items.shortdescr does not exist here,
probably because I did not .put() it previously. -->
{% endfor %}
Since that didn't work, I tried changing the Gql Query to shorten the string instead. But I'm quickly realizing Gql isn't like SQL. I'm trying to write queries like
select name,LEFT( description, 50 ) from furniture
With little success
I have little experience with Google AppEngine, but my understanding is that it is very closely related to Django. Your templates do not actually contain Python code, even if some of the structures you use in them look like it.
Both of your questions should be solved using template filters. If it was Django, I would use something like this for your second question:
{{ item.description|truncatewords:10 }}
For your first question (string replace), there may be no built-in filter you can use for that. You will need to write your own. Something like this;
from google.appengine.ext.webapp.template import create_template_register
register = create_template_register()
#register.filter
def replace_underscores(strng):
return strng.replace('_', ' ')
Then, in your template, you can do this:
{{ item.code|replace_underscores }}
Apart from the argument-less .fetch() call in your code, which I believe can't possibly work (you ALWAYS have to pass fetch an argument -- the max number of entities you're willing to fetch!), I can't reproduce your problem -- assigning a new attribute (including one obtained by processing existing ones) to each item just works fine in my tests.
Can you please reproduce your observed problem in as tiny as compass as possible and edit your question to include all relevant files pls? Seems to be the only way we could help you with your weird observed bug!
BTW, select name,LEFT( description, 50 ) or whatever OF COURSE won't work in GQL -- GQL, very very explicitly, ONLY supports select * to get whole entities, or select __key__ to get just the entities' keys -- that's all; NO selectivity of columns in the select, much less any OPERATIONS on them!-)

Categories