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.
Related
I am trying to switch my head to start using MVC.
I have a Base HTML template, with an include NavBar code:
{% include "navBar.html" %}
So far, so good. Now, I want to send information to it (to the navBar.html template) regarding the Menu buttons. I have some simple buttons, and others with drop-button behavior.
My buttons are objects, they have information about name, href, position, etc, type (simple-button or drop-button)
So, I created a nested list in this way:
outer_list = []
for a in UserModule.objects.filter(user=user_id, is_active=True):
inner_list = []
inner_list.append(UserModule(a))
for b in Submodule.objects.filter(module=a.module, is_active=True):
inner_list.append(Submodule(b))
outer_list.append(inner_list)
return {'outer_list': outer_list}
So, my first element in every inner_list is the head of the possible drop-button or a simple button depending on his type attribute.
The list at the end is like this:
[0] Button-Simple-A
[1] Button-Drop-A => [sub-button-1, sub-button-2, sub-button-3]
[2] Button-Simple-B
and so on.
When I pass this outer_list to the template, the thing I have to do to arrange the buttons into the menu are crazy things. It has no sense to use MVC if I am going to write a lot of code in the template.
Until now, I am doing this over the template, and It is missing the first element identification, to recognize the button type, etc...
{% with isFirst=true %}
{% for inner_list in outer_list %}
{% for object in inner_list %}
{% if isFirst == true %}
<li><a href=#>Drop_parent</a></li>
{% else %}
<li><a href=#>Drop-Child</a></li>
{% endif %}
{% endfor %}
<li><a href=#>Static Button</a></li>
{% endfor %}
{% endwith %}
It is not finished at all, but I believe I am taking the wrong way.
Good advice will be thankful.
Thanks
Finally,
I got something that works. I would like to know if this is acceptable or there is another better way.
On the view side:
for a in UserModule.objects.filter(user=user_id, is_active=True):
x = Module.objects.get(id=a.module_id, is_active=True)
if x.type == 'drop-parent':
list.append(x)
for b in Submodule.objects.filter(module=a.module_id, is_active=True):
list.append(b)
list.append('drop_end')
return {'menu_list': list}
On the template site:
{% for object in menu_list %}
{% if object.type == 'drop-parent' %}
<li class="dropdown">
{{object.name}}
<div class="dropdown-content">
{% endif %}
{% if object.type == 'drop-child' %}
<a href=#>{{ object.name }}</a>
{% endif %}
{% if object == 'drop_end' %}
</div>
</li>
{% endif %}
{% endfor %}
Another question: Why adding the class identifier inside the list, I can not see the attributes in the template? I mean list.append(Module(x)) is not seen as an object Module inside template; otherwise, if I avoid adding the class I can access the attributes.
Thanks, I appreciate it
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 %}.
I wonder how I can get a specific number of items when i put an if statement inside a for loop
i know we can do {% for i in items|slice ":5"%} to get a number of items but when i do
{% for post in posts %}
{% for img in post_imgs %}
{% if img.link == post.link %}
<img class="class" src="{{img.img.url}}" style="width:100%">
{% endif %}
{% endfor %}
{% endfor %}
there's no way of doing that inside the if tag .. any solution
From this answer:
Changing the state of an object in a Django template is discouraged.
You should probably bite the bullet, calculate the condition
beforehand and pass extra state to the template so you can simplify
the template logic.
So just do your comparisons in python in your view, something like:
post_imgs_filtered = [img for img in post_imgs if img.link == post.link]
And then in your template:
{% for img in post_imgs_filtered|slice ":5" %}
<img class="class" src="{{img.img.url}}" style="width:100%">
{% endfor %}
I seem to know where the issue is located since I can get around it, but for getting around it I have to sacrifice a function I really want to keep.
Here is the relevant code in the non-working state:
{% if sections %}
{% for item in sections %}
<a class="sections" href="{% url 'sections:generate' item.section.slug %}">{{ item.section.title }}</a>
{% for subsection in item.subsections %}
<p>{{ subsection.title }}</p>
{% endfor %}
{% endfor %}
{% else %}
<p>Error retrieving sections or no sections found</p>
{% endif %}
The problem part above is in the link tag. Let me explain by showing the related view.py:
def index(request):
sections = Section.objects.all()
context = {
'sections': [],
}
for section in sections:
context.get("sections").append(
{
'section': section,
'subsections': get_subsections(section),
}
)
return render(request=request, template_name='index.html', context=context)
So, 'sections' is an iterable list of items, containing for every items a dictionary with two entries. One, 'section' and one 'subsection'. There are multiple subsections for every section, this is what I really want to accomplish.
Ordinarily, when not bothering with subsections and simply iterating over a list of sections works fine. The template code for that would look something like:
{% for section in sections %}
{{ section.title }}
{% endfor %}
NOTE! The code above works just fine! But as soon as I add 'sections' as a list of dictionaries and have to reference the slug by item.section.slug the pages stop rendering.
Please advise.
Try using tuples:
View:
context['sections'] = [(section, tuple(get_subsections(section))) for section in sections]
Template:
{% for section, subsections in sections %}
<a class="sections" href="{% url 'sections:generate' section.slug %}">{{ section.title }}</a>
{% for subsection in subsections %}
<p>{{ subsection.title }}</p>
{% endfor %}
{% endfor %}
If I include paginator, then its printing multiple paginator on same page. because I am including in forloop. How do I solve this problem? please help
----------------------
{% autopaginate recipes %}
{% for recipe in recipes %}
{{ forloop.counter }}
{% endfor %}
-----------
here is my full code.
{% with followers=current_user.get_profile.get_following.all %}
{% for follower in followers %}
{% with recipes=follower.recipe_set.all %}
{% for recipe in recipes %}
{{ forloop.counter }}
{% endfor %}
{% endwith %}
{% endfor %}
{% endwith %}
Result - > 1 2 3 1 2 3 ...... 50. It should be 53. So I can easily use paginator
thanks
the doc string in the setup.py file of django-pagination mentions the below,
Decide on a variable that you would like to paginate, and use the autopaginate tag on that variable before iterating over it. This
could take one of two forms (using the canonical object_list
as an example variable):
{% autopaginate object_list %}
This assumes that you would like to have the default 20 results per page. If you would like to specify your own amount of
results per page, you can specify that like so:
`{% autopaginate object_list 10 %}`
Note that this replaces object_list with the list for the current page, so you can iterate over the object_list like you normally would.
Now you want to display the current page and the available pages, so somewhere after having used autopaginate, use the paginate
inclusion tag:
{% paginate %}
This does not take any arguments, but does assume that you have already called autopaginate, so make sure to do so first.
That's it! You have now paginated object_list and given users of
the site a way to navigate between the different pages--all without
touching your views.
So, where are you using paginate tag after the autopaginate? You actually need not loop through recipes, autopaginate should do that for you wherever you call paginate.