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}
Related
I want to use the following code to filter the data in models.py in views.py and output the Today_list to today.html, but when I open this url, nothing is displayed. What is the problem?
class Post(models.Model):
created =models.DateTimeField(auto_now_add=True,editable=False,blank=False,null=False)
title =models.CharField(max_length=255,blank=False,null=False)
body =models.TextField(blank=True,null=False)
def __str__(self):
return self.title
views.py
from Todolist import models
from django.views.generic import ListView
from django.utils import timezone
class TodayView(ListView):
model = models.Post
template_name ='Todolist/today.html'
def get_queryset(self):
Today_list= models.Post.objects.filter(
created=timezone.now()).order_by('-id')
return Today_list
todaylist.html
{% extends "Todolist/base.html" %}
{% block content %}
{% for item in Today_list %}
<tr>
<td>{{item.title}}</td>
</tr>
{% endfor %}
{% endblock %}
urls.py
urlpatterns=[
path('today/' ,views.TodayView.as_view() ,name='today')
]
use get_context_data to add Today_list to context
ref : https://docs.djangoproject.com/en/4.1/ref/class-based-views/generic-display/
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['Today_list'] = self.get_queryset()
return context
or you can simply use in template model.name_list in your case it will be post_list instead of today_list
{% extends "Todolist/base.html" %}
{% block content %}
{% for item in post_list %}
<tr>
<td>{{item.title}}</td>
</tr>
{% endfor %}
{% endblock %}
problem is where you want objects that created today, but your queryset filter just right now, not today.
So to achieve today's posts, you can do this:
from django.utils import timezone
def get_queryset(self):
Today_list = models.Post.objects.filter(
created__gte=timezone.now().replace(hour=0, minute=0, second=0),
created__lte=timezone.now().replace(hour=23, minute=59, second=59)
).order_by('-id')
return Today_list
this queryset returns objects that have been created today.
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
Hate to ask such a simple question (I spent hours trying to solve it). I watched tons of tutorials and posts (also on this site) all explain the same thing but I can't access my data on the template.
views.py
from django.shortcuts import render
from django.http import HttpResponse
from django.template import loader
from django.views.generic import ListView, DetailView
from .models import YTLink
def ytlinks(request):
queryset = YTLink.objects.all()
return render(request, 'links/home.html', {'queryset':queryset}, content_type='application/xhtml+xml')
home.html
{% extends "links/header.html" %}
{% block content %}
{% if queryset %}
queryset is filled
{% else %}
queryset is not filled
{% endif %}
<br> <br> <br>
{% for ytlink in queryset %}
{{ ytlink.link }}><br>
{% endfor %}
My queryset is never filled. What is wrong with this code?
try this:
def ytlinks(request):
try:
queryset = YTLink.objects.all()
except:
queryset = None
return render(request, 'links/home.html', {'queryset':queryset}, content_type='application/xhtml+xml')
in home.html
change
{% if queryset %}
to
{% if queryset is not None %}
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.
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.