django applying a style class based on a conditional - django

I am displaying a list of images.
If the user has uploaded an image, I want to keep its opacity 0.5 and in the list of images, the images uploaded by others should have full opacity.
I have done it as follows, is there a better way to do it??
{% if request.user == obj.shared_by %}
<div class="item-image" style="opacity:0.5;filter:alpha(opacity=50);">
{% else %}
<div class="item-image">
{% endif %}
......Some code here....
</div>
Thanks!

I normally go for:
<div class="item-image{% if foo %} own-image{% endif %}">...</div>
but switching out the entire div tag may be more readable.
Either way I'd do the styling with another class, not with inline css.

I have added class on if condition by this way....
<li class="nav-item {% if app_url == '/' %} active{% endif %}">

Related

Get a random object of a Wagtail page model but not the current one

So I have this template context processor:
from cases.models import CasePage
def random_case(request):
case = CasePage.objects.live().order_by('?')
return {'random_case': case}
And in the template I do this:
{% for entry in random_case %}
{% if request.get_full_path != entry.get_url %}
{% if forloop.first %}
<a class="ajax-link project-next" href="{{ entry.get_url }}">
<div class="nav-project-title">{{ entry.title }}</div>
<div class="nav-title">next</div>
</a>
{% endif %}
{% endif %}
{% endfor %}
And this works but the problem is sometimes the object is the same as the page so nothing is displayed. It would be great if that one would be skipped in favour of the next entry. And it's also too much logic in the template for me. What would be the best way to move this logic into the context processor and make it work?
Make random_case a method of CasePage, and filter out the case with an ID equal to self.
class CasePage(Page):
# ...
def random_case(self):
return CasePage.objects.live().exclude(id=self.id).order_by('?').first()
You can then refer to this method within your template as page.random_case - bear in mind that a new random choice will be made on each call, so you probably want something like {% with page.random_case as case %}.

Wagtail ListBlock - how to access first (any) element in template?

I have ListBlock called imagesin Wagtail. It works well. If I put
{{ page.images }}
in a template, it render the html code like:
<ul>
<li>item1</li>
<li>item2</li>
</ul>
But I am unable to find out how to get the first item of the list isolated. Or at least how to iterate over the list manually.
I am pretty sure the solution is simple, however I am unable to google it, find in the docs, or understand from the wagtail source.
You haven't shared your model definition, but I'm going to guess it's something like:
class MyPage(Page):
images = StreamField([
('image_list', blocks.ListBlock(blocks.ImageChooserBlock)),
])
Using the standard pattern for manually looping over a StreamField value as shown in the Wagtail docs, this would be:
{% for block in page.images %}
{% if block.block_type == 'image_list' %}
{# at this point block.value gives you the images as an ordinary Python list #}
{# Output the first image using block.value.0: #}
{% image block.value.0 width-800 %}
{# Or loop over block.value manually with a 'for' loop #}
<ul>
{% for img in block.value %}
<li>{% image img width-800 %}</li>
{% endfor %}
</ul>
{% elif block.block_type == 'some_other_block' %}
...
{% else %}
...
{% endif %}
{% endfor %}
In this case, you probably only have one block type defined (image_list), so the if block.block_type == 'image_list' can be left out; but you'll still need the outer {% for block in page.images %}, because StreamField is still defined as a list of blocks, even if you only have one item in that list.

What is the DRY way to manage complex querystrings in django?

In my django project I have two options that use querystrings to define a kind of list being fetched, e.g:
Shopping
Chores
On top of that I also want to check which list has been selected by the user and make it appear bold in the UI. So
{% if 'shopping' in request.GET.list or not request.GET.list %}
<b>Shopping</b>
Chores
{% elif 'chores' in request.GET.list %}
Shopping
<b>Chores</b>
{% endif %}
What's really confusing me now, is in addition to Shopping and Chores I also want to have two sub-options that define the order of the list. New and Old, for instance. To me it seems like the only way of doing this is with another duplication of all the code.
{% if 'new' in request.GET.list %}
{% if 'shopping' in request.GET.list or not request.GET.list %}
<b>Shopping</b>
Chores
<b>New</b>
Old
{% elif 'chores' in request.GET.list %}
Shopping
<b>Chores</b>
<b>New</b>
Old
{% endif %}
{% elif 'old' in request.GET.list %}
{# ... #}
{% endif %}
I think you can already see how insane this becomes to manage and you would still need to do the same for the Old if statement. I really don't know what to do here because I can't see any other way to (1) Know what should be bold and not bold. And (2) Known whether each option should begin with a ? or &.
Regarding your first problem with having bold selected value, by the use a of a HTML class you can do the following instead for example.
In your css file (or style block in your html file):
.selected {font-weight: bold;}
So your html can now become somehing like,
<a class="{% if 'shopping' in request.GET.list or not request.GET.list %} selected{% endif %}" href="{% url 'index' %}?list=shopping">Shopping</a>
<a class="{% if 'chores' in request.GET.list %}selected{% endif %}" href="{% url 'index' %}?list=chores">Chores</a>
This way you dont have to write your html twice or more for each case.
As for your second issue, you can do something like below if you are using your 'new' and 'old' in your urls or html,
{% with 'new old bla' as list %}
{% for option in list.split %}
<a class="{% if 'shopping' in request.GET.list or not request.GET.list %} selected{% endif %}" href="{% url 'index' %}?list=shopping&option={{ option }}">Shopping</a>
<a class="{% if 'chores' in request.GET.list %}selected{% endif %}" href="{% url 'index' %}?list=chores&option={{ option }}">Chores</a>
{% endfor %}
{% endwith %}
Thats just an example of how you would use it, but this will save alot of code writing.
Hope this helps!
You could use a QueryDict for your query strings. That's what Django uses internally.
https://docs.djangoproject.com/en/2.1/ref/request-response/#django.http.QueryDict
But really, I would consider refactoring your code. Put routing logic in your urls.py and business logic in your view functions. Try to keep the template files as uncomplicated as possible.
Instead of /?list=shopping you can use a regular url: /list/shopping/, for example.

How to add top save button on django admin change list?

I want to have a save button on top of django admin change list page. It seems that django don't have this functionality built-in. The save_on_top option only controls behavior on change form page. Any suggestion is welcome.
In Django 3 (and maybe earlier, not sure) in your custom admin form add save_on_top = True
class MyAdmin(admin.ModelAdmin):
save_on_top = True
First, you need a way to extend the template found at django/contrib/admin/templates/admin/change_list.html. If you don't already know how to do that, check out this answer and this answer.
Next, you need to create your own change_list.html template and put code similar to the following in it. For the sake of simplicity, I've included inline CSS. However, this is bad practice, so you should not do it. Assuming you move the CSS to an external file, you won't need to load admin_static. Lastly, the extends line that you use might not be exactly the same as what I've shown here.
{% extends "contrib/admin/templates/admin/change_list.html" %}
{% load i18n admin_static %}
{% block result_list %}
{% if cl.formset and cl.result_count %}
<div style="border-bottom: 1px solid #ccc; background: white url({% static "admin/img/nav-bg.gif" %}) 0 180% repeat-x; overflow: hidden;">
<p>
<input type="submit" name="_save" class="default" value="{% trans 'Save' %}"/>
</p>
</div>
{% endif %}
{{ block.super }}
{% endblock %}
The {% if %} tag and the <input> tag inside of it is from django/contrib/admin/templates/admin/pagination.html.
The CSS is based on the CSS for #changelist .paginator and is found in django/contrib/admin/static/admin/css/changelists.css.
If you don't mind having pagination links at the top of the page as well, you can do it with a few lines of template code, worksforme in Django 2.0.
Create my_app/templates/admin/my_app/my_model/change_list.html:
{% extends "admin/change_list.html" %}
{% load admin_list %}
{% block result_list %}
{% pagination cl %}
{{ block.super }}
{% endblock %}
This will render the pagination and the save button:
Could benefit from a line or two of CSS, though...

Alternate Row Coloring in Django Template with More Than One Set of Rows

Django templates offer the builtin tag cycle for alternating between several values at different points in a template (or for loop in a template) but this tag does not reset when it is accessed in a scope outside of the cycles definition. I.e., if you have two or more lists in your template, the rows of all of which you'd like to use some css definitions odd and even, the first row of a list will pick up where the last left off, not with a fresh iteration from the choices (odd and even)
E.g., in the following code, if the first blog has an odd number of entries, then the first entry in a second blog will start as even, when I want it to start at odd.
{% for blog in blogs %}
{% for entry in blog.entries %}
<div class="{% cycle 'odd' 'even' %}" id="{{entry.id}}">
{{entry.text}}
</div>
{% endfor %}
{% endfor %}
I've tried obviating this by patching with the resetcycle tag offered here:
Django ticket: Cycle tag should reset after it steps out of scope
to no avail. (The code didn't work for me.)
I've also tried moving my inner loop into a custom tag, but this also did not work, perhaps because the compile/render cycle moves the loop back into the outer loop? (Regardless of why, it didn't work for me.)
How can I accomplish this simple task!? I'd prefer not to create a data structure in my view with this information pre-compiled; that seems unnecessary. Thanks in advance.
The easiest workaround (until the resetcycle patch gets fixed up and applied) is to use the built-in "divisibleby" filter with forloop.counter:
{% for entry in blog.entries %}
<div class="{% if forloop.counter|divisibleby:2 %}even{% else %}odd{% endif %}" id="{{ entry.id }}">
{{ entry.text }}
</div>
{% endfor %}
A little more verbose, but not hard to understand and it works great.
https://docs.djangoproject.com/en/1.8/ref/templates/builtins/#cycle
{% for o in some_list %}
<tr class="{% cycle 'row1' 'row2' %}">
...
</tr>
{% endfor %}
Give up and use Jinja2 Template System
I gave up on django template language, it's very restricted in what you can do with it.
Jinja2 uses the same syntax that the django template uses, but adds many enhancements over it.
EDIT/NOTE ( I know it sounds like a big switch for just a minor issue, but in reality I bet you always find yourself fighting the default template system in django, so it really is worthwhile and I believe it will make you more productive in the long run. )
You can read this article written by its author, although it's technical, he mentions the problem of the {% cycle %} tag in django.
Jinja doesn't have a cycle tag, it has a cycle method on the loop:
{% for user in users %}
<li class="{{ loop.cycle('odd', 'even') }}">{{ user }}</li>
{% endfor %}
A major advantage of Jinja2 is that it allows you to use logic for the presentation, so if you have a list of pictures, you can put them in a table, because you can start a new row inside a table every N elements, see, you can do for example:
{% if loop.index is divisibleby(5) %}
</tr>
{% if not loop.last %}
<tr>
{% endif %}
{% endif %}
you can also use mathematical expressions:
{% if x > 10 %}
and you can access your python functions directly (but some setup is required to specify which functions should be exposed for the template)
{% for item in normal_python_function_that_returns_a_query_or_a_list() %}
even set variables ..
{% set variable_name = function_that_returns_an_object_or_something() %}
You can use tagged cycle and resetcycle (new in Django 1.11) calls (from https://docs.djangoproject.com/en/1.11/ref/templates/builtins/#std:templatetag-resetcycle ):
{% for blog in blogs %}
{% cycle 'odd' 'even' as rowcolors silent %}
{% resetcycle rowcolors %}
{% for entry in blog.entries %}
{% cycle rowcolors %}
<div class="{{ rowcolors }}" id="{{entry.id}}">
{{ entry.text }}
</div>
{% endfor %}
{% endfor %}
I end up doing so, with the forloop.counter0 - It works great!
{% for product in products %}
{% if forloop.counter0|divisibleby:4 %}<div class="clear"></div>{% endif %}
<div class="product {% if forloop.counter0|divisibleby:4 %}col{% else %}col20{% endif %}">
Lorem Ipsum is simply dummy text
</div>
{% endfor %}
The easiest answer might be: "give up and use jQuery." If that's acceptable it's probably easier than fighting with Django's templates over something so simple.
There's a way to do it server-side with an iterator that doesn't keep a simultaneous copy of all the entries:
import itertools
return render_to_response('template.html',
{
"flattened_entries": itertools.chain(*(blog.entries for blog in blogs)),
})