How do I do this in a django template:
{% if li_status.profile_exists and (op1.conns|length > 0 or op2.conns|length > 0) %}
Parentheses are illegal in this expression and I'm not sure how the expression will be evaluated without them.
I prefer to do this in a single line and not using a nested if
As danihp said, there's often no reason to do such a thing in a template.
This kind of logic should be avoided in templates, that's why Django does not provide the ability to do that.
Did you try something like this in your view?
def your_view(request):
# Stuff
condition = li_status.profile_exists and (len(op1.conns) > 0 or len(op2.conns) > 0)
return render_to_response('your-template.html',
{
'condition': condition
},
RequestContext(request)
)
Then in your template:
{% if condition %}
...
If the condition is in a loop, and operates on properties of items within that queryset (as per Ben Davis' comment), then the technique is to run the loop and decorate it before you put the result in the context. Below is one of many ways to do this:
# in the view somewhere
qs = MyObject.objects.all()
decorated = []
for item in qs:
item.field_that_does_not_exist_on_the_model = expensive(item)
decorated.append(item)
.. then you put decorated in the context, not the qs and use t like any other field:
{% for item in decorated %}
{% if item.field_that_does_not_exist_on_the_model %}
..
{% endif %}
{% endfor %}
Another bonus of doing it this way that if it is slow as heck, it is possible to optimize it. You cannot optimize queryset access after the queryset has been handed over to the template.
Related
I have two views which uses one template.
#users.route("/one")
#login_required
def one(username):
return render_template('follower.html')
and
#users.route("/two")
#login_required
def two(username):
return render_template('follower.html')
in the jinja template ( follower.html ), I am trying to execute a program if route one is used like this:
{% if url_for('users.one') %}
execute program
{% endif %}
but it seems I am doing it wrongly. Please what is the correct way of determine which route is used?
You can simply, in your template file, write a condition to check if request.endpoint equals the function name for the desired route, which in this case would be one, as seen in this example:
{% if request.endpoint == 'one' %}
execute program
{% endif %}
In this way, you will not make any changes to your route functions.
You cannot have two functions with the same name - they are both named two.
One simple way to accomplish this is to pass in a flag. E.g.,
#users.route("/one")
#login_required
def one(username):
return render_template('follower.html', one=True)
then check for it in the template
{% if one %}
execute program
{% endif %}
from two() you'd padd one=False.
I am having a problem with djangos design choice not to allow model filtering in templates. Actually, I do understand its sense and I do not really want to break it, but currently I cannot see what's the best or usual method to circumvent my situation.
I am having a model Task with a foreign key user_solutions to another model Solution. Now I am iterating over all Tasks and if the user already has a solution for this task, I want to display both a tick and the link to his solution. Somewhat like this:
{% for task in tasks %}
{{ task.title }}
{% if task.user_solutions.filter(author=author).count() > 0 %}
Tick!
{{ task.user_solutions.get(author=author).get_absolute_url }}
{% endif %}
{% endfor %}
Yes, it looks cruel querying the database two times for the same information and django template does not accept it like this (correctly).
However, the other approaches to not seem to work either:
I cannot add a method Task.get_current_user_solution(), because in the model I do not know which user is logged in
I cannot add a method Task.get_user_solution(user), because I cannot pass arguments through the template
I cannot query information in the view and save it into a dictionary current_users_solutions (with Task.id as index), because in the template, I cannot use combined variables to access dictionaries (and the index to access it would of course be task.id)
So what else is there I can do? From the linked article I can only see that I could add a new template tag to allow querying from the template, but as said, I actually would like to follow djangos design principle if possible.
The Django way to do this is to create a custom template tag that accepts a user parameter and filters the queryset appropriately. It's just a couple of lines of code.
Django isn't dogmatic about "no logic in templates" (dogmaticism is frowned on in Python generally, aka "practicality beats purity"). It doesn't provide the ability to do that sort of thing natively in the template language, but that's why it has custom template tags at all: if your design requires it, and the simplest way to do it would be to query from the template, then that's what you should do.
You can add whatever you want to your tasks while in the view, so, in views.py, you could do something like this:
# in views.py
for task in tasks:
if task.user_solutions.filter(author=author).count() > 0:
task.is_this_users = True
task.url = task.user_solutions.get(author=author).get.absolute_url
and then in your template:
{% for task in tasks %}
{{ task.title }}
{% if task.is_this_users %}
Tick!
{{ task.url }}
{% endif %}
{% endfor %}
You can use django template tags like this:
templatetags.py
#register.inclusion_tag("template.html")
def task_def(request):
task = user_solutions.filter(author=author).count()
if task >0:
task.is_this_users = True
task_url = task.user_solutions.get(author=author).get.absolute_url
return {'task_url': task_url}
in the template file (.html)
{% load templatetags %}
and now you can use your return result here like you want
{% for element in task_url %}
Good Afternoon,
How can I use a variable variable name in Django templates?
I have a custom auth system using context, has_perm checks to see if the user has access to the specified section.
deptauth is a variable with a restriction group name i.e SectionAdmin. I think has.perm is actually checking for 'deptauth' instead of the variable value SectionAdmin as I would like.
{%if has_perm.deptauth %}
How can I do that? has_perm.{{depauth}} or something along those lines?
EDIT - Updated code
{% with arg_value="authval" %}
{% lookup has_perm "admintest" %}
{% endwith %}
{%if has_perm.authval %}
window.location = './portal/tickets/admin/add/{{dept}}/'+val;
{% else %}
window.location = './portal/tickets/add/{{dept}}/'+val;
{%endif%}
has_perm isn't an object.. it's in my context processor (permchecker):
class permchecker(object):
def __init__(self, request):
self.request = request
pass
def __getitem__(self, perm_name):
return check_perm(self.request, perm_name)
You're best off writing your own custom template tag for that. It's not difficult to do, and normal for this kind of situation.
I have not tested this, but something along these lines should work. Remember to handle errors properly!
def lookup(object, property):
return getattr(object, property)()
register.simple_tag(lookup)
If you're trying to get a property rather than execute a method, remove those ().
and use it:
{% lookup has_perm "depauth" %}
Note that has_perm is a variable, and "depauth" is a string value. this will pass the string for lookup, i.e. get has_perm.depauth.
You can call it with a variable:
{% with arg_value="depauth_other_value" %}
{% lookup has_perm arg_value %}
{% endwith %}
which means that the value of the variable will be used to look it up, i.e. has_perm.depauth_other_value'.
You can try like this,
{{ dict|key:key_name }}
Filter:
def key(d, key_name):
return d[key_name]
key = register.filter('key', key)
More information, django ticket
I'm using Django to show a list of posts. Each post has a 'is_public' field, so if one post's 'is_public' equals to False, it should not be shown to the user. Also, I want to show a fixed number of posts in one page, but this number can be changing depending on views.
I decided to crop the queryset in template as a few views are using the same template, generating it in the view means a lot of repeated codes.
If written in python, it should look like this:
i=number_of_posts_to_show_in_one_page
while i:
if qs[i].is_public == True:
#show qs[i] to the page
i--
As the django template does not support while loop and for loop seems hard to control, is there a way of achieving this? Or should I do it in another way?(One idea is to crop the qs before looping)Thanks!
Update:
I've written this template tag to pre-process the queryset:
#register.simple_tag(takes_context=True)
def pre_process_list(context,list,numbers):
#if not user.has_perm('admin'):
context['result_list']=list.filter(is_public=True, is_removed=False)[0:numbers]
#else:
#context['result_list']=list[0:numbers]
return ''
Before using for loop in the template, I'll pass the queryset to this templage tag, and use a simple for loop to show its result.
If in the future I want to show non-public posts to admins(which is not decided yet), I can write in some logic like the commented ones, and have them styled differently in the template.
{% for post in posts %}
{% if post.is_public %}
{{ post }}
{% endif %}
{% endfor %}
Though this would be a perfect use case for a manager.
You could write a simple manager that filters public posts.
class PublicPostManager(models.Manager):
def get_query_set(self):
return super(PublicPostManager, self).get_query_set().filter(is_public=True)
Then you would add it to your Post Class:
class Post(models.Model):
...
public = PublicPostManager()
Then you could pass post.public.all() as public_posts to your template and simplify your loop:
{% for post in public_posts %}
{{ post }}
{% endfor %}
#arie has a good approach with the manager, but you can easily do the same without writing a manager:
# View
posts = Post.objects.filter(is_public=True) # or use the manager
# Now, you can either limit the number of posts you send
# posts = posts[:5] (only show five in the view)
return render_to_response('foo.html',{'posts':posts})
# Template
# Or you can do the limits in your template itself:
{% for post in posts|slice:":5" %}
{{ post }}
{% endfor %}
See the slice filter on more information.
However, since this is a common operation, with django 1.3 you can use class based views to automate most of this.
I'm implementing a custom permissions application in my Django project, and I'm lost as to how to implement a custom template tag that checks a logged in user's permissions for a specific object instance and shows a piece of HTML based on the outcome of the check.
What I have now is (pseudocode):
{% check_permission request.user "can_edit" on article %}
<form>...</form>
{% endcheck %}
('check_permission' is my custom template tag).
The templatetag takes in the user, the permission and the object instance and returns the enclosed HTML (the form). This currently works fine.
What I would like to do however, is something like:
{% if check_permission request.user "can_edit" on article %}
<form>...</form>
{% else %}
{{ article }}
{% endif %}
I've read about the assignment tag, but my fear is that I would pollute the context variable space with this (meaning I might overwrite previous permission context variables). In other words, as the context variables are being defined on different levels (the view, middleware in my case, and now this assignment template tag), I'm worried about maintainability.
You can use template filters inside if statements. So you could rewrite your tag as a filter:
{% if request.user|check_can_edit:article %}
Note that it's tricky to pass multiple arguments of different types to a filter, so you'll probably want to use one filter per permission, above I've used check_can_edit.
You can definitely do that if you're willing to write some more lines of python code to improve your template readability! :)
You need to parse the tag content yourself, even the parameters it takes and then resolve them, if you want to use variables on them.
The tag implemented below can be used like this:
{% load mytag %}
{% mytag True %}Hi{% else %}Hey{% endmytag %} Bro
Or with a variable:
{% mytag myobject.myflag %}Hi{% else %}Hey{% endmytag %} Bro
So, here's the way I did it:
from django.template import Library, Node, TemplateSyntaxError
register = Library()
#register.tag
def mytag(parser, token):
# Separating the tag name from the "test" parameter.
try:
tag, test = token.contents.split()
except (ValueError, TypeError):
raise TemplateSyntaxError(
"'%s' tag takes two parameters" % tag)
default_states = ['mytag', 'else']
end_tag = 'endmytag'
# Place to store the states and their values
states = {}
# Let's iterate over our context and find our tokens
while token.contents != end_tag:
current = token.contents
states[current.split()[0]] = parser.parse(default_states + [end_tag])
token = parser.next_token()
test_var = parser.compile_filter(test)
return MyNode(states, test_var)
class MyNode(Node):
def __init__(self, states, test_var):
self.states = states
self.test_var = test_var
def render(self, context):
# Resolving variables passed by the user
test_var = self.test_name.resolve(context, True)
# Rendering the right state. You can add a function call, use a
# library or whatever here to decide if the value is true or false.
is_true = bool(test_var)
return self.states[is_true and 'myvar' or 'else'].render(context)
And that's it. HTH.
In Django 2 the assignment tag was replaced by simple_tag() but you could store the custom tag result as a template variable:
# I'm assuming that check_permission receives user and article,
# checks if the user can edit the article and return True or False
{% check_permission user article as permission_cleared %}
{% if permission_cleared %}
<form>...</form>
{% else %}
{{ article }}
{% endif %}
Check the current doc about custom template tags: https://docs.djangoproject.com/en/2.1/howto/custom-template-tags/#simple-tags
inside my_tags.py
from django import template
register = template.Library()
#register.simple_tag(takes_context=True)
def make_my_variable_true(context):
context['my_variable'] = True
return '' # without this you'll get a "None" in your html
inside my_template.html
{% load my_tags %}
{% make_my_variable_true %}
{% if my_variable %}foo{% endif %}
In this case best solution is to use custom filter. If you don't want write long code for custom tag. Also if you don't want to copy/paste others code.
Here is an example
Inside templatetag
register = template.Library()
def exam_available(user, skill):
skill = get_object_or_404(Skill, id=skill)
return skill.exam_available(user)
register.filter('exam_available', exam_available)
Inside template
{{ request.user|exam:skill.id }}
or
{% if request.user|exam:skill.id %}
Since one of the main common of it is to use request.user or any specific object(id) inside model's custom method, so filtering that individual object or user is the easiest way to make it done. :)