I have a variable, result, that I display in a Django template using:
{{ result }}
If I set result = "fred", it displays fine.
However, if I set result = "fred\xbf" it is not rendered in the web page.
Why is this? How can I get variables with these types of characters to display?
Are you using Python 2.x? Try prefixing your string with u. Try result = u"fred\xbf".
Sometimes templates eat exceptions and in python 2 not everything is unicode by default.
Related
Is it possible to slice the string from Django template tag's variable?
Let's say some_variable contain "abcde"
I want it to be sliced to be "abc"
On Django's template, I tried like this.
{{some_variable[:-2]}}
It does not work.
If it's possible to slice words from Django template tag's variable, please advise me how to do it.
Yes, you can work with the |slice template filterĀ [Django-doc]:
{{ some_variable|slice:":-2" }}
This works both for lists and strings. For example:
>>> from django.template import Template, Context
>>> Template('{{ foo|slice:":-2" }}').render(Context({'foo': 'abcde'}))
'abc'
Using {{ some_variable[:-2] }} is not possible: Django's template language does not allow function calls, subscripting, operators, etc. Only a sublanguage of Python is supported, mainly to prevent people from writing business logic in the templates.
I am trying to display ValuesQuerySet list to drop down list in django template page. I jus to filter special characters while displaying in drop down. I tried autoescape syntax but it doesn't work. Is anyother way to do this.
in views.py:
email_accounts = EmailAccount.objects.filter(user__user=self.request.user).values()
form.fields['account'].queryset = email_accounts.values_list('a_email')
Here the value should like [{'a_email': u'xx#gmail.com'}, {'a_email': u'yy#gmail.com'}, {'a_email': u'zzz#gmail.com'}].
In template page
{{ form.account }}
So it displayed like below in drop down list
(u'xx#gmail.com')
(u'yy#gmail.com')
(u'zz#gmail.com')
I need to remove (u') those special chars when displaying in to drop down list. How to do that? any one suggest me.
You shouldn't be using a ValuesQueryset at all here. The queryset parameter for a ModelChoiceField expects, not surprisingly, a standard queryset.
email_accounts = EmailAccount.objects.filter(user__user=self.request.user)
form.fields['account'].queryset = email_accounts
I'm a python and django newbie.
This is in my html template
<input type ="checkbox" value={{ item.id }} name="ck1[]">
In views.py when i do a checked = request.POST.get(['ck1']) i get unhasable list error. Kindly guide me.
Please don't use PHP syntax when you're writing Django. name="ck1[]" is a PHP-ism that's completely unnecessary.
If you want the field to be called ck1, just call use name="ck1", and use `request.POST.getlist('ck1') in your view.
If you really have to use that horrible bracket syntax, you'll need to use request.POST.getlist('ck1[]'), because Django quite sensibly believes that the name you use in the HTML is the name you should get in the POST data.
If u want to get array from html in Django view u need to use
checked = request.POST.getlist('ck1[]')
or
checked = request.POST.getlist('ck1')
getlist method will convert all selected values into python list
I am new to both Python (and django) - but not to programming.
I am having no end of problems with identation in my view. I am trying to generate my html dynamically, so that means a lot of string manipulation. Obviously - I cant have my entire HTML page in one line - so what is required in order to be able to dynamically build an html string, i.e. mixing strings and other variables?
For example, using PHP, the following trivial example demonstrates generating an HTML doc containing a table
<?php
$output = '<html><head><title>Getting worked up over Python indentations</title></head><body>';
output .= '<table><tbody>'
for($i=0; $i< 10; $i++){
output .= '<tr class="'.(($i%2) ? 'even' : 'odd').'"><td>Row: '.$i;
}
$output .= '</tbody></table></body></html>'
echo $output;
I am trying to do something similar in Python (in my views.py), and I get errors like:
EOL while scanning string literal (views.py, line 21)
When I put everything in a single line, it gets rid of the error.
Could someone show how the little php script above will be written in python?, so I can use that as a template to fix my view.
[Edit]
My python code looks something like this:
def just_frigging_doit(request):
html = '<html>
<head><title>What the funk<title></head>
<body>'
# try to start builing dynamic HTML from this point onward...
# but server barfs even further up, on the html var declaration line.
[Edit2]
I have added triple quotes like suggested by Ned and S.Lott, and that works fine if I want to print out static text. If I want to create dynamic html (for example a row number), I get an exception - cannot concatenate 'str' and 'int' objects.
I am trying to generate my html dynamically, so that means a lot of string manipulation.
Don't do this.
Use Django's templates. They work really, really well. If you can't figure out how to apply them, do this. Ask a question showing what you want to do. Don't ask how to make dynamic HTML. Ask about how to create whatever page feature you're trying to create. 80% of the time, a simple {%if%} or {%for%} does everything you need. The rest of the time you need to know how filters and the built-in tags work.
Use string.Template if you must fall back to "dynamic" HTML. http://docs.python.org/library/string.html#template-strings Once you try this, you'll find Django's is better.
Do not do string manipulation to create HTML.
cannot concatenate 'str' and 'int' objects.
Correct. You cannot.
You have three choices.
Convert the int to a string. Use the str() function. This doesn't scale well. You have lots of ad-hoc conversions and stuff. Unpleasant.
Use the format() method of a string to insert values into the string. This is slightly better than complex string manipulation. After doing this for a while, you figure out why templates are a good idea.
Use a template. You can try string.Template. After a while, you figure out why Django's are a good idea.
my_template.html
<html><head><title>Getting worked up over Python indentations</title></head><body>
<table><tbody>
{%for object in objects%}
<tr class="{%cycle 'even' 'odd'%}"><td>Row: {{object}}</td></tr>
{%endfor%}
</tbody></table></body></html>
views.py
def myview( request ):
render_to_response( 'my_template.html',
{ 'objects':range(10) }
)
I think that's all you'd need for a mockup.
In Python, a string can span lines if you use triple-quoting:
"""
This is a
multiline
string
"""
You probably want to use Django templates to create your HTML. Read a Django tutorial to see how it's done.
Python is strongly typed, meaning it won't automatically convert types for you to make your expressions work out, the way PHP will. So you can't concatenate strings and numbers like this: "hello" + num.
Revised question:
In my dbms, I'm storing the literal <<<firefox-image>>>, I confirmed in Navicat and Mysql CLI that its <<<firefox-image>>>. When I use the Python shell and try to grab the same article entry, the outer <>'s get converted to < and <, respectively.
Snippet of me testing:
>>> entry = Entry.objects.filter( pub_date__lte = datetime.datetime.now() ).filter(featured=1)[0].excerpt_html
>>> entry
u'<p>\u0432\u0430\u043d.\n<<<firefox-image>>></p>'
How can I get it to use the literal < and >?
Original question:
In my template I did this:
{{ entry.excerpt_html|safe|render_uploads }}
it complained at the render_uploads because I didnt load adminfiles, so I prepended
{% load adminfiles_tags %}
The error went away, but in my article excerpt it still renders <<<firefox-image>>> as <<firefox-image>>.
I'm a dumbass - I forgot to invoke render_uploads before storing it.
return markdown(render_uploads(markup))
I can't duplicate that symptom; the fact that you have only two less-than and greater-thans on each side makes me wonder if your inline syntax is wrong? Are there definitely three on either side in your content area?
Otherwise, I think I'd need to see more of the relevant code.