2

I am using Django and postgres.

My views.py looks like:

def home(request):
    title = Scrap.objects
    return render(request, 'index.html', {'headlines': headlines})

My index.html looks like:

 <div class="content"
    style="background:white; color: white; font-family: Verdana;font-weight: 5;text-align: center;">
    {% for headline in headlines.all reversed %}
        <a href="{{ headline.url }}" target="_blank" style="color:black; font-size: medium;" />{{ headline.headlines }}</a>
        <hr style="border-bottom: dotted 1px #000" />
    {% endfor %}
  </div>

With the above code I am getting all the rows from the databse. How can I get only "N" rows?

I have tried:

{% for headline in headlines.all[:5] reversed %}

but it throws an error.

Could not parse the remainder: '[:5]' from 'headlines.all[:5]'

6
  • 1
    you have no reference to headlines variable in the given view function. Is that a typo? Commented Mar 28, 2020 at 4:46
  • Is there any particular reason you are trying to do this in the template rather than the view? Commented Mar 28, 2020 at 4:46
  • @MatthewGaiser i am following a tutorial and the tutor is doing in this way. That is the only reason i am doing it in the template. Commented Mar 28, 2020 at 4:47
  • @ArakkalAbu nope, this is what i am using. I might be wrong because i am following a tutorial and trying to follow that. Commented Mar 28, 2020 at 4:49
  • Are you sure that you are using Jinga2 and not Django? As that syntax looks correct. Can you give us the specific error? Commented Mar 28, 2020 at 4:51

2 Answers 2

2

seems like you got into the wrong tutorial. This answer is may not the exact answer you may looking for, but this will give you the idea

# views.py
def home(request):
    limit = 5
    queryset = MyModel.objects.all()[:limit]
    return render(request, 'index.html', {'queryset': queryset})

# index.html
{% for headline in queryset reversed %}
    {{ headline }}
{% endfor %}
Sign up to request clarification or add additional context in comments.

1 Comment

getting this error: 'ellipsis' object is not iterable
1

If you want the latest (last N rows which are added to the database):

MyModel.objects.all().order_by('-id')[:10]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.