Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - use template tag and 'with'?

Tags:

I have a custom template tag:

def uploads_for_user(user):     uploads = Uploads.objects.filter(uploaded_by=user, problem_upload=False)     num_uploads = uploads.count()     return num_uploads 

and I'd like to do something like this, so I can pluralize properly:

{% with uploads_for_user leader as upload_count %}     {{ upload_count }} upload{{ upload_count|pluralize }} {% endwith %} 

However, uploads_for_user leader doesn't work in this context, because the 'with' tag expects a single value - Django returns:

TemplateSyntaxError at /upload/ u'with' expected format is 'value as name' 

Any idea how I can get round this?

like image 265
AP257 Avatar asked Apr 23 '10 10:04

AP257


People also ask

What is the use of template tag in Django?

Django Code The template tags are a way of telling Django that here comes something else than plain HTML. The template tags allows us to to do some programming on the server before sending HTML to the client.

How do I use custom template tags in Django?

Create a custom template tagUnder the application directory, create the templatetags package (it should contain the __init__.py file). For example, Django/DjangoApp/templatetags. In the templatetags package, create a . py file, for example my_custom_tags, and add some code to it to declare a custom tag.

What does {{ name }} this mean in Django templates?

What does {{ name }} this mean in Django Templates? {{ name }} will be the output. It will be displayed as name in HTML. The name will be replaced with values of Python variable.


2 Answers

You could turn it into a filter:

{% with user|uploads_for as upload_count %} 
like image 59
Daniel Roseman Avatar answered Nov 06 '22 03:11

Daniel Roseman


While a filter would still work, the current answer to this question would be to use assignment tags, introduced in Django 1.4.

So the solution would be very similar to your original attempt:

{% uploads_for_user leader as upload_count %} {{ upload_count }} upload{{ upload_count|pluralize }} 

Update: As per the docs assignment tags are deprecated since Django 1.9 (simple_tag can now store results in a template variable and should be used instead)

like image 43
imiric Avatar answered Nov 06 '22 03:11

imiric