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.
Related
I am trying to create a blog app which has posts and each posts have title, date, link and tags.
This is my models.py
# models.py
from django.db import models
class Tag(models.Model):
name = models.CharField(max_length=20)
def __str__(self):
return self.name
class Meta:
ordering = ('name',)
class Post(models.Model):
title = models.CharField(max_length=300)
date = models.DateTimeField()
link = models.URLField()
tags = models.ManyToManyField(Tag)
def __str__(self):
return self.title
#property
def tags_name(self):
return [x.name for x in self.tags]
class Meta:
ordering = ('date',)
This is my views.py
# views.py
from django.conf.urls import url, include
from django.views.generic import ListView
from blog.models import Post
urlpatterns = [
url(r'^$', ListView.as_view(queryset=Post.objects.all().order_by("-date"), template_name="blog/blog_list.html")),
]
This is my blog_list.html
<!-- blog_list.html -->
{% extends "mysite/layout.html" %}
{% block content %}
<h1>my blog posts</h1>
<ul>
{% for post in object_list %}
<li><span class="title">{{ post.title }}</span></li>
<p>{{ post.date|date:"d-m-Y" }}</p>
{% endfor %}
</ul>
{% endblock %}
{% block sidebar %}
<h4 id="sidenav">tags</h4>
{% for post in object_list %}
<ul>
<!-- I want to show the tags here -->
</ul>
{% endfor %}
{% endblock %}
In the blog_list.html, I am showing all the post details and on the sidebar, I want to show all the tags present from all the blog posts available. Since post.tags is ManyToManyField, how can I iterate through it?
You want to use .all in the template to get all the elements in the relationship:
{% for tag in post.tags.all %}
{{ tag }}
{% endfor %}
Thanks to #hansTheFranz for correcting my bracket issue.
Regarding not repeating tags, this would be very difficult with the current context. You might want to look into instead getting the posts in your View and extracting the tags there, where you have more freedom to check for duplicates. Something like this:
def tags(request):
posts = Post.objects.all()
tag_list = []
for post in posts:
tags = post.tags.all()
for tag in tag:
if not (tag in tag_list):
tag_list.append(tag)
context_dict = { "tags": tag_list, "posts": posts }
return render(request, 'blog/blog_list.html', context_dict)
urlpatterns = [
url(r'^$', tags, name="tags"),
]
And then change your template to be more like:
{% block sidebar %}
<h4 id="sidenav">tags</h4>
<ul>
{% for tag in tags %}
<li>{{ tag }}</li>
{% endfor %}
</ul>
{% endblock %}
Additionally, instead of referencing object_list you can now access the list of posts by referencing posts, because we have defined the list of posts as such in our context dictionary, which is being passed to the template.
I'm afraid I have not tested this and it may not be very efficient, but roughly speaking it should work. A lecturer at my university wrote this book: http://www.tangowithdjango.com/book17/, which encourages more of a style of writing views as I have done: separate from the URLs. If anything I've done seems unclear or contrary, you may want to have a look at the book and see if anything there makes more sense.
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'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.
I am making a django blog and want to show a list of comments for each blog post, but I have trouble figuring out how to reference the comments in the views and the templates.
My models are defined like this:
class Issue(models.Model):
title = models.CharField(max_length=255)
text = models.TextField()
author = models.ForeignKey(User)
def __unicode__(self):
return self.title
class Comment(models.Model):
commenter = models.ForeignKey(User)
issue = models.ForeignKey(Issue)
text = models.TextField()
and my views like this
class IssueDetail(DetailView):
model = Issue
context_object_name = "issue"
template_name = "issue_detail.html"
def get_context_data(self, **kwargs):
context = super(IssueDetail, self).get_context_data(**kwargs)
context['comments'] = Comment.objects.all()
return context
class CommentDetail(DetailView):
model = Comment
context_object_name = "comment"
template_name = "comment_detail.html"
and finally the issue_detail.html template
{% block content %}
<h2>{{ issue.title }}</h2>
<br/>
<i>As written by {{ issue.author.first_name }}</i>
<br/><br/>
<blockquote> {{ issue.text }}</blockquote>
<h3>Comments</h3>
{% for comment in comments %}
<li>{{comment}}</li>
{% endfor %}
{% endblock %}
This allows me to reference the fields of the comment inside the Issue template, but basically then I want the comments to have a template of their own that will be rendered inside the for loop. What is the correct way to do this in Django?
The comments are already available in your template because of the model relationship you defined. You can delete the get_context_data in IssueDetail.
Your issue_detail.html template could look like this:
{% for comment in issue.comment_set.all %}
{% include 'comment_detail.html' %}
{% endfor %}
Your comment_detail.html template could look like this:
<ul>
<li>{{ comment.issue }}</li>
<li>{{ comment.text }}</li>
</ul>
what if this we were using a different model
product = models.ForeignKey(Customer)
how would we do the CRUD opertions from the templates an the views.py