У меня есть этот блок кода в моем 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')