-
Website
http://blog.perplexedlabs.com/ -
Original page
http://blog.perplexedlabs.com/2009/08/13/adventures-in-django-and-python-part-iii/ -
Subscribe
All Comments -
Community
-
Top Commenters
-
Max "WorldMaker" Battcher
1 comment · 1 points
-
TJ Mapes
1 comment · 1 points
-
Traveller_Adventure
1 comment · 2 points
-
Joe Devon
1 comment · 1 points
-
Shai
1 comment · 1 points
-
-
Popular Threads
-
Setup Python 2.6.4, mod_wsgi 2.6, and Django 1.1.1 on CentOS 5.3 (cPanel)
4 weeks ago · 1 comment
-
Setup Python 2.6.4, mod_wsgi 2.6, and Django 1.1.1 on CentOS 5.3 (cPanel)
value_when_true if condition else value_when_false
3 if a==2 else 101
introduced in v2.5.
Using the and-or hack you will run into problems, it's not recommended
[] and 'true' or false
is false for example.
I just wanted to let you know, Python (2.5 and up I believe) does in fact have a ternary operator; it's just a slightly different syntax. In your example, I could go:
label = "true" if booleanVariable else "false"
Unfortunately, it's fairly recent, so if you use it and then end up on an old version (< 2.5 I believe), you'll be in trouble.
if account.useraccount_set.filter(user__exact=request.user) != []:
you could try:
if account.useraccount_set.filter(user__exact=request.user).count()
or if you do need the result:
try:
user_account = account.useraccount_set.get(user=request.user)
...
except UserAccount.DoesNotExist:
....
I suppose using the 2nd method you proposed, count(), would be ideal for performance/memory reasons because you're not transferring the result-set from the database.
title = forms.CharField(attrs={'class': 'myclass'})
Anyway the point is you say styling doesn't belong in Python and I would argue it doesn't belong in the template either.
Even if you ultimately style the attributes using CSS you have to specify that class somewhere. I'd like to able to easily do that from within the template.
@register.filter
def with_attrs(value, arg):
args = arg.split(' ')
attrs = {}
for v in args:
v1 = v.split('=')
attrs[v1[0]] = v1[1]
return value.as_widget(attrs=attrs)
{{ form.name|with_attrs:"maxlength=10" }}
Perhaps splitting on something other than a space?
might be better to write it so it can be chained:
{{ form.name|with_attrs:"size=10"|with_attrs:"style=width: 720px" }}
@register.filter
def with_attrs(value, arg):
attrs = {}
for x in arg.split(','):
v = x.strip().split('=')
attrs[v[0]] = v[1]
return value.as_widget(attrs=attrs)
{% field form.somefield class="special" %}
In the process I hacked up the automatic form generation a fair bit - unfortunately not all the required pieces were exposed by newforms at the time, which was very irritating since I don't expect to have python modules have functions I'm not allowed to get to somehow. I expect many of the specifics have changed but the basic idea might still work, though not cleanly.