Циклы Django в HTML идут не по порядку - PullRequest
0 голосов
/ 28 июня 2018

У меня есть этот блок кода в моем HTML-шаблоне:

<main role="main">
    <div class="container">
        <h1 class="text-center pt-5">welcome to my blogs</h1>
        <br>
        <br>
        <h2>my latest blog</h2>
        <hr/>
        {% for e in allblogs.all %}
        <a href="{% url 'blog_detail' e.id %}"><h1>{{ e.title }}</h1></a>
        <h6>{{ e.pretty_time }}</h6>
        <img class="img-fluid" height="400" width="300" src="{{ e.image.url }}">
            <p>{{ e.summary }}</p>
        {% endfor %}
    </div>
</main>

Как получилось, что сначала выводится /blog/2, а затем /blog/1? не петли из 1 в первую очередь? Я не мог найти ответ.

Выход:

<a href="/blog/2/"><h1>second blog</h1></a>
        <h6>Jun 26 2018</h6>
        <img class="img-fluid" height="400" width="300" src="/media/image/ben-tatlow-635718-unsplash.jpg">
            <p>second blog with new picturefirst blog pictures in something is fun to learn, but it takes lots of t</p>

        <a href="/blog/1/"><h1>first blog</h1></a>
        <h6>Jun 26 2018</h6>
        <img class="img-fluid" height="400" width="300" src="/media/image/aaron-burden-649463-unsplash.jpg">
            <p>first blog pictures in something is fun to learn, but it takes lots of time, at same time I would ha</p>

        <a href="/blog/3/"><h1>third blog</h1></a>
        <h6>Jun 26 2018</h6>
        <img class="img-fluid" height="400" width="300" src="/media/image/caleb-lucas-434609-unsplash.jpg">
            <p>even more pictures first blog pictures in something is fun to learn, but it takes lots of time, at s</p>

views.py

from django.shortcuts import render, get_object_or_404
from .models import Blog

# Create your views here.
def allblogs(request):
    allblogs = Blog.objects
    return render(request, 'blog/allblogs.html', {'allblogs':allblogs})

def blog_detail(request, blog_id):
    blogdetail=get_object_or_404(Blog, pk=blog_id)
    return render(request, 'blog/blog_detail.html', {'blog': blogdetail})

models.py

from django.db import models
from datetime import datetime

# Create your models here.
class Blog(models.Model):
    title = models.CharField(max_length=300, blank=True)
    image = models.ImageField(upload_to="image/")
    text_body = models.TextField(blank=True)
    pub_date = models.DateTimeField(default=datetime.now, blank=True)

    def __str__(self):
        return self.title

    def summary(self):
        return self.text_body[:100]

    def pretty_time(self):
        return self.pub_date.strftime('%b %e %Y')

Ответы [ 2 ]

0 голосов
/ 28 июня 2018

Вы должны использовать метод order_by в поле зрения.

#views.py
def allblogs(request):
    allblogs = Blog.objects.all().order_by("id")
    return render(request, 'blog/allblogs.html', {'allblogs':allblogs})
0 голосов
/ 28 июня 2018

Сначала я получил вывод /blog/2, а затем /blog/1 из кода ниже. Учитывая этот код, не должен ли blog/1 выводиться до blog/2 из моего цикла?

HTML-шаблон:

<main role="main">
    <div class="container">
        <h1 class="text-center pt-5">welcome to my blogs</h1>
        <br>
        <br>
        <h2>my latest blog</h2>
        <hr/>
        {% for e in allblogs.all %}
        <a href="{% url 'blog_detail' e.id %}"><h1>{{ e.title }}</h1></a>
        <h6>{{ e.pretty_time }}</h6>
        <img class="img-fluid" height="400" width="300" src="{{ e.image.url }}">
            <p>{{ e.summary }}</p>
        {% endfor %}
    </div>
</main>

Просмотров: 1010 * *

from django.shortcuts import render, get_object_or_404
from .models import Blog

# Create your views here.
def allblogs(request):
    allblogs = Blog.objects
    return render(request, 'blog/allblogs.html', {'allblogs':allblogs})

def blog_detail(request, blog_id):
    blogdetail=get_object_or_404(Blog, pk=blog_id)
    return render(request, 'blog/blog_detail.html', {'blog': blogdetail})

Модель:

from django.db import models
from datetime import datetime

# Create your models here.
class Blog(models.Model):
    title = models.CharField(max_length=300, blank=True)
    image = models.ImageField(upload_to="image/")
    text_body = models.TextField(blank=True)
    pub_date = models.DateTimeField(default=datetime.now, blank=True)

    def __str__(self):
        return self.title

    def summary(self):
        return self.text_body[:100]

    def pretty_time(self):
        return self.pub_date.strftime('%b %e %Y')

Выход:

<a href="/blog/2/"><h1>second blog</h1></a>
        <h6>Jun 26 2018</h6>
        <img class="img-fluid" height="400" width="300" src="/media/image/ben-tatlow-635718-unsplash.jpg">
            <p>second blog with new picturefirst blog pictures in something is fun to learn, but it takes lots of t</p>

        <a href="/blog/1/"><h1>first blog</h1></a>
        <h6>Jun 26 2018</h6>
        <img class="img-fluid" height="400" width="300" src="/media/image/aaron-burden-649463-unsplash.jpg">
            <p>first blog pictures in something is fun to learn, but it takes lots of time, at same time I would ha</p>

        <a href="/blog/3/"><h1>third blog</h1></a>
        <h6>Jun 26 2018</h6>
        <img class="img-fluid" height="400" width="300" src="/media/image/caleb-lucas-434609-unsplash.jpg">
            <p>even more pictures first blog pictures in something is fun to learn, but it takes lots of time, at s</p>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...