HTML double for-loop

While working on my website's HTML file, I encountered a challenge with nested for-loops. The first loop successfully checks the user's account and displays the corresponding data, and the second loop filters data starting with "Title:" and displays it flawlessly.

{% for item in user.Doc.all %}

However, when I tried to nest the loops to display specific content, it didn't work as expected. Even after researching different approaches, such as moving the logic to views.py instead of handling it in the HTML file, I couldn't find a solution that worked. Here is the code snippet that is causing trouble:

{% for item in user.Doc.all %}
    {% for post in item.templates %}
        {{ post.content }}
    {% endfor %}
{% endfor %}

Despite adding conditionals before the loops, no data was displayed. I have explored resources like this and this, which mention forloop.parentloop, but the issue persists. Any guidance would be appreciated!

Below is an excerpt from my views.py showcasing the setup:

def docpostlistview(request):
    docs = DocPost.objects.all()
    context = {"docs": docs}

    context['templates'] = DocPost.objects.filter(title__startswith="Temp: ")
    return render(request, 'my_app/docpost_list.html', context)

EDIT:

    class DocPost(models.Model):
        user = models.ForeignKey(User, default=True, related_name="Doc", on_delete=models.PROTECT)
        title = models.CharField(max_length=100)
        content = HTMLField(blank=True, null=True)

    class Meta:
        ordering = ['-pk']

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('doc-post-list')

Answer №1

If you want to filter and assign the queryset to another attribute, you can do it like this:

def documentListView(request):
    context = {}
    context['documents'] = Document.objects.filter(
        <strong>user=request.user</strong>,
        title__startswith='Temp: '
    )
    return render(request, 'my_app/document_list.html', context)

Then you can iterate over the documents without using nested loops:

{% for doc in <strong>documents</strong> %}
    {{ doc.content }}
{% endfor %}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

CSS media query to target specific viewport width

In my JavaScript code, I am dynamically creating a meta viewport. I set the value of this viewport to be 980px using the following script: var customViewPort=document.createElement('meta'); customViewPort.id="viewport"; customViewPort.name = "vie ...

Remove the bottom border from the active tab by utilizing the <div> and <a> elements

I am facing an issue with a tabbed menu on my webpage. While the menu is functioning correctly, I am struggling to remove the bottom border from the active tab. You can view all of my test code here. While I have come across solutions using <ul> an ...

Difficulties encountered when adjusting the size or reducing the images in a Cycle2 slideshow

Greetings to all fellow coders! Thank you for taking the time to read this post. I am currently facing a challenge in my web development project where I am trying to make my Cycle 2 slideshow images resize and reposition alongside other divs when the wind ...

What could be causing this strange striping effect in the radial gradient?

What causes the striped effect in the radial gradient code provided on this website: click here to view body { background: rgba(216,215,221,1); background: -moz-radial-gradient(center, ellipse cover, rgba(enter code here216,215,221,1) 0%, rgba(0,9 ...

Refresh the HTML content within a specified div element

In my index.html, there is a graph (created using d3.js) along with some code that displays a stepper with a number of steps equal to the child nodes of the clicked node: <div ng-include="ctrl.numlab==2 && 'views/stepper-two-labs.htm ...

Click to move directly to a specific section

This question may be common, but despite my research efforts, I have been unable to find a solution. I want to issue a disclaimer that I am new to javascript and jQuery. Here is an overview of what I am trying to achieve: I want two images that, when cli ...

Incorporate text onto an image using Semantic UI

Currently, I am utilizing Semantic UI to display images. While it is functioning well for me in terms of adding text near the image, I desire to have the text positioned on top of the image. Ideally, I would like it to be located on the lower half of the i ...

Employing the html.validationmessagefor to display a client-side error notification

My text fields have server-side validation messages. The field 'title' is a required field on the server side with a '[Required]' data attribute in the class, but it only seems to be checked on a postback or form submit. I am saving the ...

Struggling to dynamically append additional textboxes to a <div> element using JavaScript

After spending over 12 hours on this problem, I am completely stuck and frustrated. I have tried countless variations and sought out other solutions to no avail. It should be a simple task. My project involves using JQueryMobile 1.2 along with its dependen ...

Adjust the size and orientation of an image according to the dimensions of the window and the image

As I delve into HTML and Javascript, I am facing a challenge with resizing an image based on the window size. The goal is for the image to occupy the entire window while maintaining its aspect ratio during resizing. Additionally, if the window size exceeds ...

Ensure that the submit button triggers the display of results with each click

My project involves two navigation bars, each with its own table displayed upon page load. Additionally, there is a search bar used to display search results in another table. The issue I'm encountering is that when I click the submit button once, th ...

Using Python and Selenium to Retrieve and Load All Website Comments

I am trying to extract around 7000 comments from this link. The challenge is that the website only displays 10 comments at a time, so I am using Selenium in Python to load all comments and then parse them with BeautifulSoup. Here is the HTML segment of th ...

Guide on configuring the AutoIt path in Python

I am encountering an issue while trying to automate file uploads using the AutoIt library in combination with Selenium and Python. When executing the code, I receive the following error message: from .autoit import options, properties, commands File &quo ...

Can you tell me the specific location in the CSS where this logo image is defined?

I've been working on a website at http://onofri.org/WP_BootStrap/ and I'm facing an issue. When using FireBug, I can't seem to locate where in the CSS the image logo.png is defined (this is the small image in the upper-left corner of the the ...

Load the iframe element only when the specified class becomes visible within the container div, without relying on jQuery

I am facing a unique challenge where the performance of my page is significantly impacted by loading multiple iframes. These iframes are contained within popup modals, and I would like to delay their loading until a user clicks on the modal. When the mod ...

Utilizing values from .properties files in Java with Spring for internationalization: A straightforward approach to handle Strings

Here is the code snippet I am using: @Value("${app.user.root}") private String userRoot; This code helps me to fetch a constant value from my application.properties file. Within my GetMapping method, I need to redirect to the error page and pass a S ...

Issues with margin and padding-top not functioning properly when using @media for printing

Is there a way to add some space between the top of my webpage and my logo? I've tried adjusting the padding in my CSS, but when I check the print preview in Chrome, no spacing is visible. Below is my HTML code: <div class="container"> < ...

Retrieve JSON data within an HTML element, where the element is sourced from an AJAX GET response

What is the best way to extract JSON data from the response below? $.get('http://localhost:8000/json', function(response) { alert(response); }); The response is as follows: <div id="dom-target" style="display: none;"> {"logo":"log ...

Error message: "Maximum width header anomaly"

I've been working on a full-width header tumblr theme and everything looks great until I resize the screen to a smaller size, like on a mobile or tablet. The header ends up cutting off and no longer maintains its full width. You can see an example of ...

I can't seem to figure out the source of this TypeError. It's related to using actin for stellar activity indices and specifically mentions that it expected a string, bytes, or os

The package I am utilizing can be accessed at the following link: https://github.com/gomesdasilva/ACTIN and it is used to determine activity indices for a binary system. After running the code on a test file in spyder, everything seems to be functioning co ...