Is there a way to use a flag variable in a template? - django

I'm looping through a result set and when a certain condition is met I want to run through a conditional statement. After that condition has been met I want to continue looping through the result set without running through that condition.
Does anyone have any ideas on how I could go about this?
Edit:
Here is what I'm trying to achieve.
{% flag = false %}
{% for row in results %}
{{ row.field }}
{% if row.is_active and !flag %}
<br />
{% flag = true %}
{% endif %}
{% endfor %}

It seems that you want to do one thing with the first part of the QuerySet, and other thing with the rest. Split it in the view.
views.py
def split_list(list, condition):
list1, list2 = [], []
condition_satisfied = False
for element in list:
if not condition_satisfied and condition(element):
condition_satisfied = True
if not condition_satisfied:
list1.append(element)
else:
list2.append(element)
return list1, list2
def your_view(request):
results = YourModel.objects.all()
results1, results2 = split_list(results, condition)
return render(request, 'template.html', {
'results1': results1,
'results2': results2
})
template.html
{% for result in results1 %}
{% if result == whatever %}
<p>Condition satisfied</p>
{% else %}
<p>Condition not satisfied</p>
{% endif %}
{% endfor %}
{% for result in results2 %}
{{ result }}
{% endfor %}

Django doesn't have this feature, and for good reason. Templates should not contain this kind of logic. It should be done within the View.

Related

Calling function with "if" inside a "for" loop in django not working

{% if "Anonymous" == i.verifiedUser %} doesnt seem to work despite i.verifiedUser being valid. I can write anything else where "i.verifiedUser" is, and it will still show the same. How can i fix this?
index.html:
<div class="comments">
{% for i in comment %}
{% if "Anonymous" == i.verifiedUser %}
<small>{{i.verifiedUser}}</small>
{% else %}
<small class="verifiedUser">{{i.verifiedUser}}</small>
{% endif %}
{% endfor %}
</div>
views.py:
def question(request, questionId):
question = Qna.objects.get(id=questionId)
comment = Comment.objects.filter(questionId=questionId).order_by('-timestamp')
otherQuestions = Qna.objects.all()[:10]
return render(request, 'index/question.html', {'question':question, 'comment':comment, 'otherQuestions':otherQuestions})

Django template nested for loop with if statement not working

I need to have a nested loop in my Django template, where the outer loop goes through a list of objects, and the inner loop goes through a list of those object id's, and I want to only do something for the id's on the inner list, it never executes however. I think it has something to do with the condition for the if statement, because if I replace it with a true statement it works but it doesn't work as it is now
(I have checked to see that the id's overlap)
{% for outer in outer_obj_list %}
{% for inner_id in inner_id_list %}
{% if outer.id == inner_id %}
// do something
console.log({{inner_id}});
console.log({{outer.id}});
{% endif %}
{% endfor %}
{% endfor %}
Syntax seems correct. I would just verbosely output everything.
Perhaps it should be something like this:
{% for main_obj in main_obj_list %}
main_obj: {{ main_obj }}
{% for obj_id in obj_id_list %}
obj_id: {{ obj_id}}
main_obj: {{ main_obj.id}}
{% if main_obj.id == obj_id %}
// do something
match: {{main_obj.id}} == {{obj_id}} ;
{% endif %}
{% endfor %}
{% endfor %}
Brother I am also face this problem so my clever mind get some clever solution about this problem we can do that with JavaScript easily so we need to run it in JavaScript and then.
{% for outer in outer_obj_list %}
{% for inner_id in inner_id_list %}
if(outer.id == inner_id.id ){
console.log({{inner_id.id}});
console.log({{outer.id}});
//And also if we reserve place in DOM then we can
//change the inner Html of them easily like.
//demo = document.getElementById("demo");
//demo.innerHTML = inner_Id.id or outer.id
}
{% endfor %}
{% endfor %}

for loop iteration in django

My coding is:
views
def showThread(request, thread_id)
post_list = Post.objects.filter(id = thread_id)
post_likes = PostLikes.objects.all()
return render_to_response('show.html',locals(),context_instance=RequestContext(request))
models:
class Post(models.Model):
subject = models.CharField(max_length = 250)
body = models.TextField()
thread = models.ForeignKey('self', null = True, editable = False )
Show.html:
{% for post in post_list %}
{{post.id}}{{post.subject}}
{% endfor %}
{% for post_like in post_likes %}
{% if post_like.post_id == post.id and post_like.user_id == user.id %}
U like this post{{post}}
{% else %}
{{post}}
{% endif %}
{% endfor %}
In the show.html, else part, it displays the values again and again. But i need only one time.How can i break the for loop when i enter into else condition.Please help me..
Django's for tag doesn't provide you with any means to break out of the loop. You'll simply have to filter the collection in your own view and slice it after the point your condition fails and supply that to your template.
You can use the django custom template tag found in this django snippets page. If you have doubts on using it, go to this page to learn about custom template tags.
Then load the template tag in your template using {% load loop_break %}. Then you can break the for loop as given below:
{% for post_like in post_likes %}
{% if post_like.post_id == post.id and post_like.user_id == user.id %}
U like this post{{post}}
{% else %}
{{post}}
{{ forloop|break }}
{% endif %}
{% endfor %}
Here the for loop will break when it enters the else part.
you could probably use ifchanged tag:
https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#ifchanged
However, you probably should consider moving this logic to view.
If you can structure your if statement to detect when you want to output nothing, you can simply put nothing inside your else clause:
{% for post_like in post_likes %}
{% if post_like.post_id == post.id and post_like.user_id == user.id %}
U like this post{{post}}
{% else %}
{% if forloop.first %}
{{post}}
{%else%}{%endif%}
{% endif %}
{% endfor %}
The above might not do quite what you want - you will have to tweak it yourself. The only thing you can't do is set a flag that this is the first entry into the else clause.

Django TemplateSyntax: Two tests with an 'If .. or...'

I am trying to run two tests:
{% if profile.id != 100 or profile.location == NULL %}
however it seems to not work. I couldn't find in the docs why this isn't working. Any ideas?
EDIT:
In the SQL db, the value for profile.location is NULL. The rendered result is None.
EDIT 2:
Here is the full chain. There are 4 ways to grab a user's location. It is a giant mess as you can see...
{% if profile.city.id != 104 or profile.city %}
{{profile.city}}
{% else %}
{% if profile.mylocation != '' %}
{{ profile.mylocation }}
{% else %}
{% if profile.fbconnect == 1 and profile.location != '' and profile.location != "None" %}
{{profile.location}}
{% else %}
{% if profile.sglocation.city %}{{profile.sglocation.city}}{% else %}{{profile.sglocation.country}}{% endif %}
{% endif %}
{% endif %}
{% endif %}
There's no NULL. Try:
{% if profile.id != 100 or not profile.location %}
If I were you, I would throw all that logic back into Python, for example:
class Profile(models.Model):
[your model fields and stuff]
def get_location(self):
[your location logic]
Then in the template you can just do:
{{ profile.get_location }}

How to know if a checkbox is checked having just the {{ form.checkbox }} form-tag

How can I know if a checkbox is checked (True, 1) having just the {{ form.checkbox }} form-tag?
'activo' is defined as (True, 1) in the db.
My template is:
{{ form.activo }}
RESULTS:
<input id="id_activo" type="checkbox" name="activo" checked="checked"/>
{{ form.activo.data }}
RESULTS:
False
{{ form.activo.value }}
RESULTS:
""
Yet no 1's or True's are coming through. :S
Any hint is appreciated. =')
It is checked if request.POST.has_key('activo') or the {{ form.activo.data }} actually returns True when initialized with request.POST.
Your question isn't quite clear, but maybe your problem has something to do with the fact, that browsers don't put anything in the POST data for an unchecked checkbox.
This made things complicated for me when I had to differentiate between a checkbox not being displayed at all and a displayed checkbox not having been checked. Just from looking at the POST data you can't tell those two cases apart.
Following on from your reply to mbarkhau's answer, using instance= doesn't make the form bound, it just provides default values to the form.
Here's the logic in a template:
{% if form.is_bound %}
{% if form.initial.activo %}
Checked.
{% else %}
Not checked.
{% endif %}
{% else %}
{% if form.activo.data %}
Checked.
{% else %}
Not checked
{% endif %}
{% endif %}
But it makes more sense to do this logic in the view and pass extra context. Something like:
context_data = {...}
if form.is_bound:
activo = form.data.get('activo')
else:
activo = form.initial.get('activo')
context_data['activo'] = bool(activo)
return render_to_response('your_template.html', context_data)
If you want a boolean condition in templates this should work:
{% if form.activo %}
--
{% else %}
---
{% endif %}