I am trying to build my blog using Django 1.8 however I do not know how can I order the blogs. See the image
I want to display the 'earliest' at the bottom and the 'latest' at the top. Here is my
index.html
{% extends 'layouts/base.html' %}
{% block title %}
Homepage - {{ block.super }}
{% endblock title %}
{% block content %}
<center>
{% for blog in blogs %}
<h2><a href="{% url 'blog_detail' slug=blog.slug %}">
{{ blog.name }}
</a></h2>
<p>{{ blog.description }}</p>
{% endfor %}
</center>
{% endblock content %}
models.py
# -*- coding: utf-8 -*-
from django.db import models
from django.utils import timezone
class blog(models.Model):
name = models.CharField(max_length=255)
description = models.TextField()
slug = models.SlugField(unique=True)
date_time = models.DateTimeField(auto_now_add = True)
def __unicode__(self):
return self.name
def get_image_path(instance, filename):
return '/'.join(['blog_images', instance.bupimg.slug, filename])
class Upload(models.Model):
bupimg = models.ForeignKey(blog, related_name="uploads")
image = models.ImageField(upload_to=get_image_path)
views.py
from django.shortcuts import render
from blogging.models import *
def index(request):
blogs = blog.objects.all()
return render(request, 'index.html', {
'blogs':blogs,
})
def blog_detail(request, slug):
article = blog.objects.get(slug=slug)
uploads = article.uploads.all()
return render(request, 'blogs/blog_detail.html', {
'article': article,
'uploads': uploads,
})
How can I move the blog title 'earliest' to the downside ,'latest' on top side? I need let the latest blog shows on the top.
You are not sorting the blogs, they come in a random order. Try changing the line
blogs = blog.objects.all()
to
blogs = blog.objects.order_by('-date_time')
The minus (-) denotes descending sort, ie. from the latest to the oldest.
Related
Thank you for taking the time to help! I've been stuck for hours. I'm learning django by going through this fantastic youtube video: https://www.youtube.com/watch?v=sm1mokevMWk&t=4252s. I believe I copied the code from the video exactly, and I double and triple checked it. Yet, despite declaring method = "post" in "create".html django consistently uses a get response. WHY?!
#urls.py
from django.urls import path
from . import views
urlpatterns = [
path('<int:id>', views.index, name='index'),
path("",views.home, name = 'home'),
path("create/", views.create, name="create"),
]
#views.py
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from .models import ToDoList, Item
from .forms import CreateNewList
def index(response, id):
ls = ToDoList.objects.get(id=id)
return render(response, 'main/list.html', {"ls":ls})
def home(response):
return render(response, "main/home.html", {})
def create(response):
print(response.method)
if response.method == "POST":
form = CreateNewList(response.POST)
if form.is_valid():
n = form.cleaned_data['name']
t = ToDoList(name=n)
t.save()
return HttpResponseRedirect("/%i" %t.id)
else:
form = CreateNewList()
return render(response, "main/create.html", {"form":form})
#create.html
{% extends 'main/base.html' %}
{% block title %} Create New List {% endblock %}
{% block content %}
Create Pages
<form method="post" action="/create/">
{{form.as_p}}
<button type="submit", name ="save" >Create New</button>
</form>
{% endblock %}
#base.html
<html>
<head>
<title>{% block title %}Jeff's website{% endblock %}</title>
</head>
<body>
<div id="content", name="content">
{% block content %}
{% endblock %}
</div>
</body>
</html>
#home.html
{% extends 'main/base.html' %}
{% block title %}
Home
{% endblock %}
{% block content %}
<h1>Home Page</h1>
{% endblock %}
#models.py
from django.db import models
class ToDoList(models.Model):
name = models.CharField(max_length=200)
def __str__(self):
return self.name
class Item(models.Model):
todolist = models.ForeignKey(ToDoList, on_delete=models.CASCADE)
text = models.CharField(max_length=300)
complete = models.BooleanField()
def __str__(self):
return self.text
You need to perform a GET request first to display your form and then , you make a post request for the submit, that why you check the request method .
if response.method == "POST" => The form is already displayed and we need to submit it
else we need to display our form
I have the following blog project :
models.py:
from django.db import models
from django.utils import timezone
class Post(models.Model):
title = models.CharField(max_length=200)
body = models.TextField()
pub_date = models.DateTimeField(default=timezone.now)
categories = models.ManyToManyField('Category')
def __str__(self):
return self.title
class Category(models.Model):
title = models.CharField(max_length=200)
def __str__(self):
return self.title
# Change the name in Admin from categorys to categories
class Meta:
verbose_name_plural = "categories"
views.py:
from django.shortcuts import render
from .models import Post, Category, Comment
def getPosts(request):
posting = Post.objects.all().order_by('-pub_date')
categories = Category.objects.all()
context = {
'posting':posting,
'categories':categories,
}
return render(request, 'posts/getPosts.html', context)
getPosts.html template :
{% if posting %}
{% for article in posting %}
<h3>{{article.title}}</h3>
<ul>{{article.body}}</ul>
<ul>Posted : {{article.pub_date}}</ul>
<ul>
<em>Found in category : </em>
{{ article.categories }}
{{ article.categories.all }}
{% for category in categories %}
{{category.title}}
{% endfor %}
</ul>
{% endfor %}
{% endif %}
I have three posts, which all display properly, but
{{article.categories}} is giving me:
posts.Category.None
{{article.categories.all}} gives me
QuerySet [<Category: Diving>]
And the second loop outputs the list of all categories, which I expected as just a test run:
Kit & Packing Diving Places Tips Private
I am trying to simply pull through the category name for each post, which has been selected in the admin panel and saved through the admin panel.
I have tried what feels like a thousand different suggestions, such as changing the view to category = post.category_set.all(), and have been researching this for days now, but am getting no-where.
You already have the right answer; article.categories.all, which you should loop over.
{% for category in article.categories.all %}
{{category.title}}
{% endfor %}
You don't need the categories value in the view at all.
I'am begginer in Django so please try to understand me.
I have a problem with the blocks in my django project. I created the base.html like this
{% include 'firmy/header.html' %}
<html>
<body>
<h4>Ostatnio dodane</h4>
{% block firmy %}
{% endblock %}
<h4>Kategorie</h4>
{% block kategorie %}
{% endblock %}
</body>
{% include 'firmy/footer.html' %}
</html>
and {%block firmy%} showing me every records what I want from another file but the {%block kategorie%} showing nothing.
in views.py I have the code:
from django.shortcuts import render
from .models import Witryna, Kategorie
from django.utils import timezone
def widok_strony(request):
firmy = Witryna.objects.filter(data_publikacji__lte=timezone.now()).order_by('data_publikacji')
return render(request, 'firmy/widok_strony.html', {'firmy': firmy})
def widok_kategorii(request):
kategorie = Kategorie.objects.all().order_by('glowna')
return render(request, 'firmy/widok_kategorii.html', {'kategorie': kategorie})
and in urls.py i have the code :
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.widok_strony, name='widok_strony'),
url(r'^$', views.widok_kategorii, name='widok_kategorii'),
]
and on the end models.py
from django.db import models
from django.utils import timezone
class Kategorie(models.Model):
glowna = models.CharField(max_length=150, verbose_name='Kategoria')
class Meta:
verbose_name='Kategoria'
verbose_name_plural='Kategorie'
def __str__(self):
return self.glowna
class Witryna(models.Model):
nazwa = models.CharField(default="", max_length=150, verbose_name = 'Nazwa strony')
adres_www = models.CharField(max_length=70, verbose_name='Adres www')
slug = models.SlugField(max_length=250, verbose_name='Przyjazny adres url')
email = models.CharField(max_length=100, verbose_name='Adres e-mail')
text = models.TextField(max_length=3000, verbose_name='Opis strony')
kategoria = models.ForeignKey(Kategorie, verbose_name='Kategoria')
data_publikacji = models.DateTimeField(blank=True, null=True, verbose_name='Data publikacji')
class Meta:
verbose_name='Strona www'
verbose_name_plural = 'Strony www'
def publikacja(self):
self.data_publikacji=timezone.now()
self.save()
def __str__(self):
return self.nazwa
and widok_kategorii.html
{% extends 'firmy/base.html' %}
{% block kategorie %}
{% for kategoria in kategorie %}
<p>{{ kategoria.glowna }}</p>
{% endfor %}
{% endblock kategorie %}
Really I don't know where is the problem but when I open the browser on localhost:8000 the I can't see the details from class Kategorie.
You have a huge misconception about how views and URLs work.
A URL can only be served by one view. That view will be entirely responsible for creating the response, which it usually does by rendering a single template. You need to pass all the information for your template from that view.
I'm just built my django project but have some problem. I want to display title that is in Academy. When I run python manage.py runserver everything is okay but the title is not displayed. I don't know what the problem is.
class.html
{% extends "base.html" %}
{% block content %}
<div>
<div style="margin-top: 200px;">
</div>
{% for academy in academys %}
<h3>{{ academy.title }}</h3>
{% endfor %}
</div>
{% endblock %}
urls.py
...
url(r'^academy/class', 'academy.views.class', name='class'),
views.py
from django.shortcuts import render, Http404
from .models import Academy
def class(request):
template = 'academy/class.html'
try:
academys = Academy.objects.all()
context = {'academy': academys}
except Academy.DoesNotExit:
raise Http404
if request.user.is_authenticated():
return render(request, template, context)
else:
return HttpResponseRedirect("/account/login/")
models.py
...
class Academy(models.Model):
title = models.CharField(max_length=50)
def __unicode__(self):
return self.title
Your context dictionary key is incorrect. Instead of
context = {'academy': academys}
type
context = {'academys': academys}
You've passing 'academy' in your context not 'academys'
context={'academys ': academys}
This is my index.html file:
{% extends "base_site.html" %}
{% block content %}
{% if info %}
<ul>
{% for object in info %}
{{ Hello }}
{% endfor %}
</ul>
{% else %}
<p>No objects are available.</p>
{% endif %}
{% endblock %}
This is my views.py
from django.shortcuts import render
from django.http import HttpResponse
from django.template import RequestContext, loader
from notendur.models import *
from django.views import generic
class IndexView(generic.ListView):
template_name = 'notendur/index.html'
context_object_name = "info"
def get_queryset(self):
"""Return the last five published polls."""
return Information.objects.all()
This is my models.py:
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Information(models.Model):
title = models.CharField(max_length = 200)
body = models.TextField()
date = models.DateTimeField()
def __unicode__(self):
return self.title
class InformationChild(models.Model):
information = models.ForeignKey(Information)
child_text = models.CharField(max_length = 200)
def __unicode__(self):
return self.child_text
When I start the server, however, nothing appears. This has to be some url-link issue, because the else clause doesn't even activate. Perhaps you want urls.py as well?
Let me know if you need further information.
The error is not in the use of info, it's in what's inside the for loop: {{ Hello }} is not an item in the context. Use {{ object.title }}, for example.