in django template unable to show content inside if block - django

when i write if statement nothing show in html but when i remove the if statement the code show all items what is wrong
{% for catagory in catagory_list %}
{% for item in product_list %}
{% if item.catagory == "Fruits" %}
<p>{{item.catagory}}</p>
<p>{{item.name}}</p>
<p>{{item.price}}</p>
<img src="{{item.image.url}}" alt="">
{% endif %}
{% endfor %}
{% endfor %}

Because catagory is an Object, Try:
{% if item.catagory.name == "Fruits" %}
assuming that catagory model has an attribute "name"

Related

Django: Add class to a div depending on a variable

I'd like to declare in the template a variable that allows me to position an image inside a section on the left or the right. I just don't understand how can I do it on the variable side.
Here's my current code,
main.html :
{% with img_left=False %}
{% include 'section-service.html' %}
{% endwith %}
section-service.html:
<div class="sect_service-inside {% if img_left=True %} serv_img-left {% else %} serv_img-right {% endif %}">
<div id="here_img">...</div>
<div id="here_text">...</div>
</div>
but I get the error Could not parse the remainder: '=True' from 'img_left=True'
Note that I'll use this section multiple times in the main.html page, that's why I'd like to have the variable left-right.
EDIT:
views.py:
def page(request):
return render(request, 'main.html')
I suppose you want widget-tweaks
As example for form:
{% for field in form %}
{% if <something> %}
{% render_field field class="<first class>" %}
{% elif <something other> %}
{% render_field field class="<second class>" %}
{% else %}
{% render_field field class="<other class>" %}
{% endif %}
{% endfor %}

If statement in my Django template...Is there a better way?

In my Django template: I'm trying to add an extra div around my for loop only if the length of the data being passed to the template is 3. This is what I'm trying right now but it seems like there could be better way than doing two if statements to check for the length:
{% if items|length == 3 %}
<div class='three-item-wrap'>
{% endif %}
{% for item in items %}
.......
{% endfor %}
{% if items|length == 3 %}
</div> //close .three-item-wrap
{% endif %}
you can try like that
{% if items|length == 3 %}
<div class='three-item-wrap'>
{% for item in items %}
.......
{% endfor %}
</div>
{% else %}
#another logic goes here
{% endif %}
if you want know more refer the docs django if tempalate
I think better way would be to make single if statement check. Just like this:
{% if items|length == 3 %}
<div class='three-item-wrap'>
{% for item in items %}
.......
{% endfor %}
</div>
{% else %}
{% for item in items %}
.......
{% endfor %}
{% endif %}
This way is better because of Django render engine, which firstly check if statements and then do for loop.
And if something crash in your code, div will be without closing tag </div>. Instead in my code there is no option for div to be without closing tag.

Django template: check for empty query set

Is there a way to check for an empty query set in the Django template? In the example below, I only want the NOTES header to be displayed if there are notes.
If I put an {% empty %} inside the "for" then it does display whatever is inside the empty tag, so it knows it's empty.
I'm hoping for something that does not involve running the query twice.
{% if notes - want something here that works %}
NOTES:
{% for note in notes %}
{{note.text}}
{% endfor %}
{% endif %}
Clarification: the above example "if notes" does not work - it still displays the header even with an empty query set.
Here's a simplified version of the view
sql = "select * from app_notes, app_trips where"
notes = trip_notes.objects.raw(sql,(user_id,))
return render_to_response(template, {"notes":notes},context_instance=RequestContext(request))
Edit: the view select selects from multiple tables.
Have a look at the {% empty %} tag.
Example from the documentation
<ul>
{% for athlete in athlete_list %}
<li>{{ athlete.name }}</li>
{% empty %}
<li>Sorry, no athletes in this list.</li>
{% endfor %}
</ul>
Link: https://docs.djangoproject.com/en/1.8/ref/templates/builtins/#for-empty
If you are interested in a table, or some kind of heading if there are results, add the forloop.first:
{% for athlete in athlete_list %}
{% if forloop.first %}
Athlete Name:
{% endif %}
{{ athlete.name }}
{% empty %}
Sorry, no athletes in this list.
{% endfor %}
Try {% if notes.all %}. It works for me.
In your view check whether notes is empty or not. If it is then you pass None instead:
{"notes": None}
In your template you use {% if notes %} as normal.
It's unfortunate that you're stuck using a raw query set - they're missing a lot of useful behavior.
You could convert the raw query set into a list in the view:
notes_as_list = list(notes)
return render_to_response(template, {"notes":notes_as_list},context_instance=RequestContext(request))
Then check it as a boolean in the template:
{% if notes %}
Header
{% for note in notes %}
{{ note.text }}
{% endfor %}
{% endif %}
You could also make it happen without conversions using forloop.first:
{% for note in notes %}
{% if forloop.first %}
Header
{% endif %}
{{ note.text }}
{% endfor %}
What about:
{% if notes != None %}
{% if notes %}
NOTES:
{% for note in notes %}
{{ note.text }}
{% endfor %}
{% endif %}
{% else %}
NO NOTES AT ALL
{% endif %}
Your original solution
{% if notes %}
Header
{% for note in notes %}
{{ note.text }}
{% endfor %}
{% endif %}
Works now with Django 1.7 and thanks to QuerySet caching, it does not cost and extra query.
Often the right way to do this is to use the {% with ... %} tag. This caches the query so it runs only once and also gives you more flexibility with your markup than using {% empty %}.
{% with notes as my_notes %}
{% if my_notes %}
<ul>
{% for note in my_notes %}
<li>{{ note }}</li>
{% endfor %}
</ul>
{% else %}
<p>Sorry, no notes available</p>
{% endif %}
{% endwith %}
With this particular example I'm not sure how useful it is but if you're querying Many-to-Many field, for instance, it's likely what you want to do.
Use {% empty %} in django templates
{% if list_data %}
{% for data in list_data %}
{{ data.field_1 }}
{% endfor %}
{% else %}
<p>No data found!</p>
{% endif %}
We can write above code with {% empty %}.
{% for data in list_data %}
{{ data.field_1 }}
{% empty %}
<p>No data found!</p>
{% endfor %}

Django admin add custom button in change form depending on a form field value

I have an application that overrides het Django change form. What I want to change is the submit buttons on the bottom. Underneath is change_form.html in a django app:
{% extends "admin/change_form.html" %}
{% block submit_buttons_bottom %}
## add some buttons
{% endblock %}
The button I want to show/add depends on the value of a certain field in the form names 'status'. How can I get the value of a field in the template... something like:
{% if form.field.status == 'unresolved' %}
<input type="submit" value="Mark as resolved" class="default" name="_save" />
{% endif %}
UPDATE:
I'm not getting any errors. There is simply nothing displayed.
Looping through var 'adminform' will get me to the field I need
{% for fieldset in adminform %}
{% for line in fieldset %}
{% for field in line %}
{% if field.field.name == 'status' %}
this is status {{ field.field.name }} - {{ field.contents }}
{% endif %}
{% endfor %}
{% endfor %}
{% endfor %}
But I want to access it directly. Something like:
{% if adminform.0.0.field.status == 'unresolved' %}
<input type="submit" value="Mark as resolved" class="default" name="_save" />
{% endif %}
This should work:
{% if adminform.form.status.value == 'unresolved' %}
or if the field is readonly, there's another way:
{% if adminform.form.instance.status == 'unresolved' %}
Try changing your if statement to -
{% if adminform.status.value == 'unresolved' %}
I'm guessing, but I think the adminform variable is probably just a form. Have a look at this section of the docs to see the atributes of the form fields.

How can I get a variable passed into an included template in django

I am a Django newbie and am unable to achieve something trivial. Please help me with this.
I am setting a variable pgurl in my views.py
Am able to access the variable {{pgurl}} in my with_tag.html template. This template includes a pagination.html template into itself
In pagination.html I am unable to use the variable {{pgurl}} and nothing is printed
How can I get this variable passed into the included template?
views.py
def with_tag(request, tag, template_name='main/with_tag.html', current_page=1, pgurl=''):
if request.method == 'GET':
query_tag = Tag.objects.get(name=tag)
primes = TaggedItem.objects.get_by_model(Prime, query_tag)
primes = primes.order_by('-date')
request.page = current_page
tcm_pp = TCM_ITEMS_PER_PAGE
pgurl = request.path
else:
return HttpResponseRedirect(request.path)
return direct_to_template(request, template_name, { 'primes' : primes, 'prime_total' : Prime.objects.count(), 'now': datetime.now(), 'page' : current_page, 'tcm_pp' : tcm_pp, 'tag' : tag, 'pgurl' : pgurl })
with_tag.html
{% extends "base.html" %}
{% load comments %}
{% load pagination_tags %}
...
{% include "pagination.html" %}
{% paginate %}
pagination.html
{% if is_paginated %}
{% load i18n %}
<div class="pagination">
{% if page_obj.has_previous %}
‹‹ {% trans "previous" %}
{% else %}
<span class="disabled prev">‹‹ {% trans "previous" %}</span>
{% endif %}
{% for page in pages %}
{% if page %}
{% ifequal page page_obj.number %}
<span class="current page">{{ page }}</span>
{% else %}
{{ page }}
{% endifequal %}
{% else %}
...
{% endif %}
{% endfor %}
{% if page_obj.has_next %}
{% trans "next" %} ››
{% else %}
<span class="disabled next">{% trans "next" %} ››</span>
{% endif %}
</div>
{% endif %}
It will be helpful if you post the output of the rendered page. The context should get passed, might be your template tags instead. Try to do assert and check to see if the variables were passed correctly.