Nothing is shown in a tag - python

Nothing is shown in a tag.
I wrote in views.py
def top(request):
content = POST.objects.order_by('-created_at')[:5]
category_content = Category.objects.order_by('-created_at')[:5]
return render(request, 'top.html',{'content':content,'category_content':category_content})
in models.py
class Category(models.Model):
name = models.CharField(max_length=100)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.name
in top.html
<ul class="list-group">
<li class="list-group-item active text-center">category</li>
<div class="collapse">
{% for category in category_content %}
<a href="" class="list-group-item">
{{ category.name }}
</a>
{% endfor %}
</div>
</ul>
Now output is like
so category.name is not shown.My ideal output is
I really cannot understand why category.name is not shown.I print out print(category_content) in views.py's top method,so , ]> is shown.How should I fix this?What is wrong in my codes?

Categories are not visible, because you used collapse CSS class in the div, which means it's not displayed.
If you check Bootstrap 4 documentation on collapse, you'll see that it states
.collapse hides content

Related

In views.py file ==> category_posts = Post.object.filter(category=cat) returns an empty query set. The 'Post' model has sample posts with categories

I am creating a blog application in django where i encountered this unusual issue. I am not being able to filter and display blog posts category wise. Please find my code below. Thanks in advance. I have spent two full days trying to figure this out and still
got nothing.
MODELS.py
This is the model which i have created for a blog post.
class Post(models.Model):
title = models.CharField(max_length=255)
author = models.ForeignKey(User, on_delete=models.CASCADE)
body = models.TextField()
post_date = models.DateField(auto_now_add=True)
category = models.CharField(max_length=255, default="uncategorized")
def __str__(self):
return self.title + ' | ' + str(self.author)
def get_absolute_url(self):
#return reverse('article-detail', args=(str(self.id)))
return reverse('homepage')
VIEWS.py
This is the view that i have created for a category wise blog posts.
def CategoryView(request,cat):
category_posts = Post.objects.filter(category=cat)
return render(request,'categories.html',{'category_posts':category_posts})
URLS.py
The urls.py file.
path('category/<str:cat>/', CategoryView, name = 'category'),
CATEGORIES.html
This will be the final display page where the category_posts is displayed as an empty queryset. The for loop is unable to run because category_posts is an empty queryset. Single word categories are also empty(to rule out a slugify issue)
{% extends 'base.html' %}
{% load static %}
{% block content %}
<ul>
{% for post in category_posts %}
<li>
<div class="category">
{{ post.category }}
</div>
<a href="{% url 'article-detail' post.pk %}">
<h3><b>{{ post.title }} </b></h3>
<p class=card-date>
<big>{{ post.author }}</big>
<small>-{{ post.post_date }}</small>
</p>
<p class="excerpt-text">{{ post.body | slice:"100" |safe}}</p>
<div class="article-thumbnail">
<img src="{% static "images/bg.png" %}" alt="article-thumbnail" >
</div>
<div class="overlay">
</a>
</li>
{% endfor %}
{% endblock %}

how show favorite list in django

I have a list of favorites and I want to show them when I click on the interest button after I click on the list and my heart will be bold. The second part, ie filling the heart, is done correctly, but when I want to show the list, it does not show anything and gives the following error.
Reverse for 'show_Book' not found. 'show_Book' is not a valid view function or pattern name.
model.py
class Book (models.Model):
BookID= models.AutoField(primary_key=True)
Titel=models.CharField(max_length=150 )
Author=models.ForeignKey('Author',on_delete=models.CASCADE)
Publisher=models.ForeignKey('Publisher',on_delete=models.CASCADE) translator=models.ForeignKey('Translator',null='true',blank='true',on_delete=models.SET_NULL)
favorit=models.ManyToManyField('orderapp.Customer',related_name='favorit', blank=True)
view.py
def show_Book(request,BookID):
showBook=get_object_or_404(Book,BookID=BookID)
is_favorite=False
if showBook.favorit.filter(id=request.user.id).exists():
is_favorite=True
return render (request , 'showBook.html', {'is_favorite':is_favorite,})
def favoritbook (request, BookID):
showBook=get_object_or_404(Book,BookID=BookID)
if showBook.favorit.filter(id=request.user.id).exists():
showBook.favorit.remove(request.user)
else:
showBook.favorit.add(request.user)
return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
def favoritlist(request):
user=request.user
favoritbooks=user.favorit.all()
context={'favoritbooks':favoritbooks}
return render (request,'favotritlist.html',context)
url.py
path('showbookstor/<int:id>', views.show_BookStor, name='show_BookStor'),
path('books/favorit/<int:BookID>/', views.favoritbook, name='favoritbook'),
path('books/favorit/', views.favoritlist, name='favoritlist'),
showbook.html
{% if is_favorite %}
<li id="sell">add to favorit <i class="fas fa-heart"></i> </li>
{% else %}
<li id="sell"> delete favorit <i class="far fa-heart"></i> </li>
{% endif %}
favoritlist.html
{% for Book in favoritbooks %}
<section id="card" class="col-md-6 col-lg-3 col-sm-6 col-xs-12">
<img src= {{Book.Image.url}}>
<h1 id="bookname">{{Book.Titel}}</h1>
<p>{{Book.Author}}</p>
</section>
{% endfor %}
you use {% url 'show_Book' Book.BookID %} but you don't have any definition in the urls.py with name show_Book try changing
path('showbookstor/<int:id>', views.show_BookStor, name='show_BookStor')
to
path('showbook/<int:id>', views.show_Book, name='show_Book')

Django for loop in html template not displaying

So I am trying to get the latest post and I ran into a problem where it will not display the post
views.py
def latest_post(request):
latest = Post.objects.all().order_by('-id')[:1]
context = {'latestPost': latest}
return render(request, 'latest_post.html', context)
Note: I also tried it with this, latest = Post.objects.all()
There are entries in the database, I tested with the shell
from blog.models import Post
>>> Post.objects.all()
<QuerySet [<Post: test>, <Post: okay so>, <Post: okay-okay>]>
latest_post.html
{% for newest in latestPost %}
<section class="hero is-primary is-medium">
<div class="hero-body header">
<div class="container">
<div class="font">
<h1 class="title is-1">
<span id="blog_title">{{ newest.title }}</span>
</h1>
<h2 class="subtitle is-3 subup">
<span id="blog-subtitle">{{ newest.content|truncatechars:20|safe }}</span>
</h2>
<h2 class="subtitle is-5 dateup">
<span id="blogdate">{{ newest.timestamp }}</span><br><br>
Read More >>
</h2>
</div>
</div>
</div>
</section>
{% endfor %}
in my blog_index.html I have the following
{% extends "blog_base.html" %}
{% block blog_main %}
{% load staticfiles %}
{% include 'latest_post.html' %}
<p> other html here </p>
{% endblock %}
Latest_post.html displays when i use {% include 'latest_post.html' %} only if I don't use
{% for newest in latestPost %}
{% endfor %}
So i am sure there aren't any typos somewhere that prevents the latest_post.html from displaying in my index page.
my models.py
class Post(models.Model):
title = models.CharField(max_length=120)
slug = models.SlugField(unique=True)
content = models.TextField()
draft = models.BooleanField(default=False)
publish = models.DateField(auto_now=False, auto_now_add=False)
updated = models.DateTimeField(auto_now=True, auto_now_add=False)
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
def __str__(self):
return self.title
def blog_url(self):
return reverse("blogposts:blogdetail", kwargs={"slug": self.slug})
Additional Notes: python3, django 1.11, sqlite.
Also, No errors are displayed in the console. any help would be appreciated! thank you!!
Looks like you are passing context variable to latest_post.html directly:
return render(request, 'latest_post.html', context)
But there is no such context variable latestPost in blog_index.html.
What you need to do is add context to blog_index.html. Add this to index view also:
latest = Post.objects.all().order_by('-id')[:1]
context = {'latestPost': latest}
return render(request, 'blog_index.html', context)
Also you can use first to select first element in queryset.
In your previous code you are limiting it by using [:1] so it only returns one item. Then you are using a forloop again on one item. Not the best way to do things.
Are you trying to get only one item from the post? If yes, Forloop is not needed change your latest_post.html to
<section class="hero is-primary is-medium">
<div class="hero-body header">
<div class="container">
<div class="font">
<h1 class="title is-1">
<span id="blog_title">{{ latestPost.title }}</span>
</h1>
<h2 class="subtitle is-3 subup">
<span id="blog-subtitle">{{ latestPost.content|truncatechars:20|safe }}</span>
</h2>
<h2 class="subtitle is-5 dateup">
<span id="blogdate">{{ latestPost.timestamp }}</span><br><br>
Read More >>
</h2>
</div>
</div>
</div>
</section>
You don't even need to use the [:1] in your views. There are better ways to do this
I also stuck in the same problem and I was damn confirmed that I was doing any silly mistakes.
Unfortunately, I found one. So,
Try this:
context = {'latest': latest}
Instead of:
context = {'latestPost': latest}
I hope it works.

Django template for loop iteration by distinct foreign key

In my app, I have 3 models: Issue, Series, and Character. The Issue model has a Series ForeignKey, and a Character ManyToManyField. Here they are simplified:
class Character(models.Model):
name = models.CharField('Character name', max_length=200)
desc = models.TextField('Description', max_length=500)
class Series(models.Model):
name = models.CharField('Series name', max_length=200)
desc = models.TextField('Description', max_length=500)
class Issue(models.Model):
series = models.ForeignKey(Series, on_delete=models.CASCADE, blank=True)
name = models.CharField('Issue name', max_length=200)
number = models.PositiveSmallIntegerField('Issue number')
date = models.DateField('Cover date')
desc = models.TextField('Description', max_length=500)
characters = models.ManyToManyField(Character, blank=True)
cover = models.FilePathField('Cover file path', path="media/images/covers")
I have a Character template that displays information about the character. I want to also display Issues the Character is in, sorted by Series.
{% extends "app/base.html" %}
{% block page-title %}{{ character.name }}{% endblock page-title %}
{% block content %}
<div class="description">
<p>{{ character.desc }}</p>
</div>
<div class="issues">
<h3>Issues</h3>
{% for series in character.issue_set.all %}
<div>
{{ series.name }}
<ul>
{% for issue in character.issue_set.all %}
{% if issue.series.name == series.name %}
<li>
<img src="/{{ issue.cover }}" alt = "{{ series.name }}" >
<p>Issue #{{ issue.number }}</p>
</li>
{% endif %}
{% endfor %}
</ul>
</div>
{% endfor %}
</div>
{% endblock content %}
Obviously, the way this currently formats is that for every issue in the set, it outputs the series title, and then each issue in the set.
<div class="issues">
<h3>Issues</h3>
<div>
Series 1
<ul>
<li>
<img src="/media/images/covers/01.jpg" alt="Series 1">
<p>Issue #1</p>
</li>
<li>
<img src="/media/images/covers/02.jpg" alt="Series 1">
<p>Issue #2</p>
</li>
</ul>
</div>
<div>
Series 1
<ul>
<li>
<img src="/media/images/covers/01.jpg" alt="Series 1">
<p>Issue #1</p>
</li>
<li>
<img src="/media/images/covers/02.jpg" alt="Series 1">
<p>Issue #2</p>
</li>
</ul>
</div>
</div>
Here's what I would like to see:
<div class="issues">
<h3>Issues</h3>
<div>
Series 1
<ul>
<li>
<img src="/media/images/covers/01.jpg" alt="Series 1">
<p>Issue #1</p>
</li>
<li>
<img src="/media/images/covers/02.jpg" alt="Series 1">
<p>Issue #2</p>
</li>
</ul>
</div>
</div>
I've researched quite a bit on templating, and I'm not seeing a way to get a listing based on distinct values. I've also tried creating a new set in my Character or Issue model that I could use to replace issue_set.all, but I have yet to get it working.
EDIT: Upon request of marcusshep, the Character view is using the generic DetailView:
class CharacterView(generic.DetailView):
model = Character
template_name = 'app/character.html'
I would use a function based view rather than a class based generic view. Reason being that your required behavior is going beyond something generic.
In your function you can build the queryset you desire instead of having to fight with the one provided by generic.DetailView.
def my_view(request, *args, **kwargs):
character = Character.objects.get(id=request.GET.get("id", None))
issues = character.issue_set.all().order_by("series__name")
return render(request, 'app/character.html', {"issues": issues})
Alternatively, you can use what you already have and override the DetailView's get_queryset() method.
class CharacterView(generic.DetailView):
model = Character
template_name = 'app/character.html'
def get_queryset():
# return correct queryset
The biggest problem though is that there will be more aspects that will need to use this set. For instance, I'll be adding Creators, Story Arcs, etc. they will have their own pages and will need to display related issues, sorted by series as well. It would be nice to have a solution that can be used by any of these templates without much code re-use.
This is a very common problem in all areas of programming. A very simple way to solve this would be to isolate the logic in one function and call that function whenever you need it.
def my_issues_query():
# find the objects you need
def my_view(request, *args, **kwargs):
issues = my_issues_query()
You can also take advantage of pythons decorator functions. (Which is my favorite approach.)
def has_issues(view_function):
def get_issues(request, *args, **kwargs):
# find all the issues you need here
# you'll only need to write this logic once.
issues = Issues.objects.filter(...)
return issues
return get_issues
#has_issues
def my_view(request, *args, **kwargs):
# this functions namespace now contains
# the variable `issues`.
# which allows for the use of the query ie.
return render(
request,
"my_templates/template.html",
{"issues":issue}
)

Python/Django - Get value of a ManyToManyField in a for tag

I can't get the image related value when I'm using {% for %} with the class Article. I tried with select_related, but I don't know how to define image to be correctly in displayed in the src="" attribute of my <img /> tag
Is there a clean way to make appear as I want?
models.py
class Image(models.Model):
gallery = models.ManyToManyField(Gallery)
name = models.CharField(max_length=100)
image = models.ImageField(upload_to='static/images/gallery')
def __str__(self):
return self.name
class Article(models.Model):
section = models.ForeignKey(Menu)
title = models.CharField(max_length=100)
text = models.TextField()
type = models.ForeignKey(Type)
image = models.ManyToManyField(Image)
def __str__(self):
return self.title
views.py
def index(request):
slider = Article.objects.all()
images = Image.objects.all()
return render(request, 'cms/index.html', locals())
template
{% for i in slider %}
<li>
<img src="{{i.image}}" alt="{{i.title}}"/>
<h2>{{i.title}}</h2>
<p>{{i.text}}, {{i.image_url}}</p>
</li>
{% endfor %}
You have to use 2 forloop for displaying images in manytomany table.
{% for i in slider %}
<li>
{% for im in i.image.all %}
<img src="{{im.image.url}}" alt="{{im.name}}"/>
{% endfor %}
<h2>{{i.title}}</h2>
<p>{{i.text}}, {{i.image_url}}</p>
</li>
{% endfor %}
Article.image is a ManyToMany field. Which image You want to display? First?
<img src="{{i.image.all.0.image.url}}" alt="{{i.title}}"/>
All?
{% for im in i.image.all %}
<img src="{{im.image.url}}" alt="{{im.name}}"/>
{% endfor %}

Categories

Resources