Django template doesn't display the model items - python

sorry, I'm very new as a member (and as developer too). I've recently started to work with Django, and I'm trying to display on a page, a list of articles with some elements (title, image, created_at, content), already done in a model.
The views, the template and the path (urls) were bilt too. But when I Run the server and open the browser it only displays the title I passed as the render parameter in the view, not the object (articles = Article.objects.all()), created in the view.
blog/models.py
from email.mime import image
from email.policy import default
from tabnanny import verbose
from turtle import update
from unicodedata import category
from venv import create
from django.db import models
from ckeditor.fields import RichTextField
from django.contrib.auth.models import User
# Create your models here.
class Category(models.Model):
name = models.CharField(max_length=100, verbose_name='name')
description = models.CharField(max_length=250, verbose_name='description')
create_at = models.DateTimeField(auto_now_add=True, verbose_name='created_at')
class Meta:
verbose_name = 'Category'
verbose_name_plural= 'Categories'
def __str__(self):
return self.name
class Article(models.Model):
title= models.CharField(max_length=150, verbose_name="title")
content= RichTextField(verbose_name='Content')
image= models.ImageField(default='null', verbose_name="Image")
public = models.BooleanField(verbose_name="Public?")
user= models.ForeignKey(User, verbose_name="User", on_delete=models.CASCADE )
categories = models.ManyToManyField(Category, verbose_name='Category', blank=True)
create_at= models.DateTimeField(auto_now_add=True, verbose_name="Created at")
update_at= models.DateTimeField(auto_now=True, verbose_name="update at")
class Meta:
verbose_name = 'Article'
verbose_name_plural= 'Articles'
def __str__(self):
return self.title
blog/views.py
from django.shortcuts import render
from blog.models import Article, Category
# Create your views here.
def list(request):
articles = Article.objects.all()
return render(request, 'articles/list.html', {
'title' : 'Articles',
'articles': articles
} )
blog/list.html
{% extends 'layouts/layout.html' %}
{% block title %}
{{title}}
{% endblock %}
{% block content %}
<h1 class= "title">{{title}}</h1>
{% for article in articles %}
<article class="article-item">
{% if article.image != 'null' and article.image|length >= 1 %}
<div class="image ">
<img src="{{article.image.url}}" />
</div>
{% endif %}
<div class="data">
<h2>
{{article.title}}
</h2>
<span class="date">{{article.create_at}}</span>
<p>{{article.content|safe}} </p>
</div>
<div class="clearfix"></div>
</article>
{%endfor%}
{% endblock %}
Any help will be very appreciated

It looks like the whole block content is not rendered - Do you have a {% block content %} in the layout.html? You can check in your browser if the source code contains the html of the content block and just the tags are missing

Related

Slug URL turns into a number when navigating to the next link in django

I tried searching for this problem here but I didn't find anything, I hope someone can help answering or sending a link to a solution on stackoverflow...
I have been creating a blog, and when I click on the post title, it goes to 'post_details.html' and in the URL shows a slug with the post title. Like here:
examplename.com/blog/brooklyn-nets-at-miami-heat-preview/
But when I click to write a comment on the post it takes me to a form page, but the slug title disappear, it just shows the post number. Like this:
examplename.com/blog/3/add-comment
Can someone explain why is this happening? I want to know how to solve this and understand from where it comes this number that shows up.
Post_detail.html
{% block content %}
<h2 class="title">
<a class="post-title" href="{{ post.get_absolute_url }}">
{{ post.title }}
</a>
</h2>
<p class="date">
Publicado em {{ post.created }} por {{ post.author }}
</p>
{{ post.body|linebreaks }}
<hr>
<h3>Comments</h3>
{% if not post.comments.all %}
Nobody commented yet...Add a comment
{% else %}
Add a comment
{% for comment in post.comments.all %}
{{ comment.name }}
{{ comment.date }}
<br>
{{ comment.body }}
{% endfor %}
{% endif %}
<a class="swen" href="{% url 'blog:list' %}">More Articles</a>
{% endblock %}
urls.py
from unicodedata import name
from django.urls import path
from . import views
app_name = 'blog'
urlpatterns = [
path("", views.PostListView.as_view(), name="list"),
path("<slug:slug>/", views.PostDetailView.as_view(), name="detail"),
path("<slug:slug>/add-comment", views.CommentView.as_view(), name="commentview")
]
models.py
from django.contrib.auth.models import User
from django.db import models
from django.urls import reverse
class Post(models.Model):
title = models.CharField(max_length=255)
slug = models.SlugField(max_length=255, unique=True)
author = models.ForeignKey(User, on_delete=models.CASCADE)
body = models.TextField()
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse ('blog:detail', kwargs={"slug":self.slug})
class Meta:
ordering = ("-created",)
class Comment(models.Model):
post = models.ForeignKey(Post, related_name="comments", on_delete=models.CASCADE)
name = models.CharField(max_length=255)
body = models.TextField()
date = models.DateField(auto_now_add=True)
slug = Post.slug
def __str__(self):
return reverse (self.post.title, self.name, self.post.slug)
views.py
from xml.etree.ElementTree import Comment
from django.views.generic import DetailView, ListView, CreateView
from .models import Post, Comment
class PostListView(ListView):
model = Post
class PostDetailView(DetailView):
model = Post
class CommentView(CreateView):
model = Comment
template_name = 'add_comment.html'
fields = '__all__'
you're passing pk which is a type integer as parameter instead of a slug at path name commentview. May be you should check on that.

How to Get Items in a model connected to another model using a foreign key in detail view in django?

I am trying to create a cartoon streaming website in which when a user clicks on their cartoon of choice(Eg:Pokemon), they get to see the seasons as a list as well as the detail of the cartoons.
from django.db import models
class Cartoon(models.Model):
name = models.CharField(max_length=200)
cover = models.ImageField()
description = models.TextField()
start_date = models.CharField(max_length=50)
end_date = models.CharField(max_length=50)
def __str__(self):
return self.name
class CartoonSeason(models.Model):
cartoon = models.ForeignKey(Cartoon, null=True, on_delete=models.SET_NULL)
number = models.IntegerField()
season_cover = models.ImageField(blank=True, null=False)
season_name = models.CharField(max_length=200, blank=True, null=True)
season_description = models.TextField(blank=True, null=False)
Here I have linked the Cartoon model with the CartoonSeason model using a Foreign Key so when a new season is to be added, it automatically gets linked with the corresponding Cartoon
from django.shortcuts import render
from django.http import HttpResponse
from django.views.generic import ListView, DetailView
from .models import CartoonSeason, Cartoon
class CartoonListView(ListView):
model = Cartoon
template_name = "index.html"
class CartoonSeasonView(DetailView):
queryset = CartoonSeason.objects.filter()
model = CartoonSeason
template_name = "season.html"
I am using a detail view to display the CartoonSeason model so that it displays the Cartoons details as well, but when I try to load the seasons, it only displays the season with the Primary Key of 1. I want it to display all of the seasons added to the cartoon.
Here's my seasons.html
{% extends 'base.html' %}
{% block title %}
test
{% endblock %}
{% block content %}
<main>
<section class="cartoon-description">
<div class="season_head">
<img src="{{object.cartoon.cover.url}}" width="260px" alt="">
<div class="cartoon-name">
<h1>{{object.cartoon.name}}</h1>
<small >{{object.cartoon.start_date}} - {{object.cartoon.end_date}}</small>
<br>
<div class="description">
<strong>Description:</strong>
<br>
<p>{{object.cartoon.description}}</p>
</div>
</div>
</div>
</section>
<hr>
</main>
{% endblock %}
Here is My urls.py
from .views import CartoonListView, CartoonSeasonView
urlpatterns = [
path('', CartoonListView.as_view(), name="home"),
path('cartoon/<int:pk>' , CartoonSeasonView.as_view(), name="cartoon"),
]
This is my main template
{% extends 'base.html'%}
{% block title %}
Home - CartoonsPalace
{% endblock %}
{% block content %}
<main>
<section class="cartoon-list">
<div class="select-text">
<h1>Pick Your Cartoon Series of Choice:-</h1>
</div>
{% for cartoon in object_list %}
<div class="list">
<a href="{% url 'cartoon' cartoon.pk %}"><div class="list-object">
<img src="{{cartoon.cover.url}}" alt="" width="184px">
<h3>{{cartoon.name}}</h3>
<span>{{cartoon.start_date}} - {{cartoon.end_date}}</span>
</div>
</a>
</div>
{% endfor %}
</section>
</main>
{% endblock %}
Any help would be appreciated.
Ok when you want to access all the objects related to another objects through foreign key , you have two simple options :
1.set query using the cartoon(reverse relation):
cartoon = Cartoon.objects.get(id = 'pk') # get the pk by passing in url
cartoon_season = cartoon.cartoonseason_set.all()
# object.(name of model CartoonSeason must be in lowercase )._set.all()
or set query using the CartoonSeason(recommended):
#before this you must have the id of the cartoon :
cartoon = Cartoon.objects.get(id = pk)
seasons = CartoonSeason.objects.filter(cartoon = cartoon)
I dont know about you cartoon template or urls, but I assume in you cartoon template where you show your cartoon detail you have a link to the season of the cartoon ,so there you should pass the id of the cartoon : {{cartoon.id}}
and in you urls you get this id to use in your season detail :
but note that when you are using DetailView and want to use that id passing by url you shoud define a get_queryset like this :
class CartoonSeasonView(DetailView):
model = CartoonSeason
template_name = "season.html"
def get_queryset(self, *args, **kwargs):
#before this you must have the id of the cartoon :
cartoon = Cartoon.objects.get(id = self.kwargs['pk'])
seasons = CartoonSeason.objects.filter(cartoon = cartoon)
and remember no need to user have query_set anymore.
by this you can show the name of the cartoon or the poster in the cartoonseason page.
and remember we user detail view in order to show detials of only one object not 7 ( like season of a cartoon ).You can use ListView or if you want to show different data in one template use TemplateView.

Django ListView not showing up in frontend

I am trying to create a gym workout basic app in Django, and wish to have my workouts displayed as a list on my home page, using Django's built-in list view. For some reason, my home page template is rendering, with the proper headers and nav bar, but my list is not showing. Here is my code:
Models.py
from django.db import models
STATUS = (
(0,"Draft"),
(1,"Publish")
)
class Workout(models.Model):
workout_number = models.AutoField(primary_key=True)
name = models.CharField(max_length=255)
created_on = models.DateTimeField(auto_now_add=True)
content = models.TextField()
description = models.TextField(blank=True, default='')
time_cap = models.TimeField(auto_now=False, auto_now_add=False, blank=True)
rounds = models.IntegerField(blank=True, default='')
weight = models.FloatField(blank=True, default='')
status = models.IntegerField(choices=STATUS, default=0)
class Meta:
ordering = ['-created_on']
def __str__(self):
return self.name
Views.py
from django.shortcuts import render
from django.views import generic
from .models import Workout
class WorkoutList(generic.ListView):
model = Workout
template_name = 'home.html'
context_object_name = 'workout'
queryset = Workout.objects.filter(status=1).order_by('-created_on')
Template home.html (part of)
<div class="container">
<div class="row">
<div class="col-md-8 mt-3 left">
{% for workout in workout_list %}
<div class="card mb-4">
<div class="card-body">
<h2 class="card-title">{{ workout.name }}</h2>
<p class="card-text text-muted h6">{{ workout.created_on}} </p>
<p class="card-text">{{workout.content|slice:":200" }}</p>
</div>
</div>
{% endfor %}
</div>
</div>
Workout/Urls.py
from django.urls import path
from . import views
app_name='workout'
urlpatterns = [
path('', views.WorkoutList.as_view(), name='home'),
]
Since the context_object_name is 'workout', this means that the list of objects is passed as workout, but you iterate over {% for workout in workout_list %}. You should change this to:
from django.shortcuts import render
from django.views import generic
from .models import Workout
class WorkoutList(generic.ListView):
model = Workout
template_name = 'home.html'
context_object_name = 'workout_list'
queryset = Workout.objects.filter(status=1).order_by('-created_on')

Django: Cannot Add Clickable Link in the Template

I am a beginner in Django. I am building a Django app, named PhoneReview. It will store reviews related to the latest mobile phone. It will also display phone brands, along with the associated phone models. I have already created models for:
Brand – details on brand, such as, name, origin, manufacturing since, etc
Model – details on model, such as, model name, launch date, platform, etc
Review – review article on the mobile phone and date published, etc
Many-to-many relationship between Review and Model.
I also have created views for the following:
a. An index page that display all Brands available for mobile phone in the database
b. A phone model page that display model when a brand is selected.
c. A detail page when a model is selected that contain reviews and newslink
Now, I am facing a problem. I cannot put any clickable link that will redirect the phone brands, like Apple and Samsung, of brandlist.html web page, to their respective phone model page (phonemodel.html). Here is the screenshot:
Here are the codes of models.py inside "PhoneReview" folder.
from django.db import models
from django.template.defaultfilters import slugify
# Create your models here.
class Brand(models.Model):
brand_name = models.CharField(max_length=100)
origin = models.CharField(max_length=100)
manufacturing_since = models.CharField(max_length=100, null=True, blank=True)
def __str__(self):
return self.brand_name
def save(self, *args, **kwargs):
self.slug = slugify(self.title)
super().save(*args, **kwargs)
class PhoneModel(models.Model):
brand = models.ForeignKey(Brand, on_delete=models.CASCADE)
model_name = models.CharField(max_length=100)
launch_date = models.CharField(max_length=100)
platform = models.CharField(max_length=100)
def __str__(self):
return self.model_name
class Review(models.Model):
phone_model = models.ManyToManyField(PhoneModel, related_name='reviews')
review_article = models.TextField()
date_published = models.DateField(auto_now=True)
slug = models.SlugField(max_length=150, null=True, blank=True)
def __str__(self):
return self.review_article
Here are the codes of urls.py inside "PhoneReview" folder.
from . import views
from django.urls import path
urlpatterns = [
path('index', views.BrandListView.as_view(), name='brandlist'),
path('phonemodel/<int:pk>/', views.ModelView.as_view(), name='modellist'),
path('details/<int:pk>/', views.ReviewView.as_view(), name='details'),
]
Here are the codes of views.py inside "PhoneReview" folder:
from django.views import generic
from .models import Brand, PhoneModel, Review
class BrandListView(generic.ListView):
template_name = 'PhoneReview/brandlist.html'
context_object_name = 'all_brands'
def get_queryset(self):
return Brand.objects.all()
class ModelView(generic.DetailView):
model = PhoneModel
template_name = 'PhoneReview/phonemodel.html'
class ReviewView(generic.DetailView):
model = Review
template_name = 'PhoneReview/details.html'
Here are the codes of apps.py inside "PhoneReview" folder:
from django.apps import AppConfig
class PhonereviewConfig(AppConfig):
name = 'PhoneReview'
Here are the codes of phonemodel.html. The page can be accessed by going through http://127.0.0.1:8000/phonemodel/1/ in the browser.
{% extends 'PhoneReview/base.html' %}
{% load static %}
{% block title%}
Phone Model Page
{% endblock %}
{% block content %}
<!--Page content-->
<h1>This is Phone Model Page</h1>
<h2>Here is the phone model</h2>
<ul>
<li>{{ phonemodel.model_name }}</li>
</ul>
<img src="{% static "images/brandlist.jpg" %}" alt="Super Mario Odyssey" /> <!-- New line -->
{% endblock %}
Here are the codes of brandlist.html. The web page can be accessed by going to http://127.0.0.1:8000/index in the browser.
{% extends 'PhoneReview/base.html' %}
{% load static %}
{% block title%}
Brand List
{% endblock %}
{% block content %}
<!--Page content-->
<h1>This is Brand List Page</h1>
<h2>Here is the list of the brands</h2>
<ul>
{% for brand in all_brands %}
<li>{{ brand.brand_name }}</li>
{% endfor %}
</ul>
<img src="{% static "images/brandlist.jpg" %}" alt="Super Mario Odyssey" /> <!-- New line -->
{% endblock %}
I tried modifying <li>{{ brand.brand_name }}</li>to <li>{{ phonemodel.model_name }}</li> . But the code doesn't work.
What should I do?
Update 1: I can't view the brandlist.html page when I add <li>{{ phonemodel.model_name }}</li>. I get an error on http://127.0.0.1:8000/index. It says 'phonemodel' is not a registered namespace
Update 2: I have managed to fix the issue. I changed the code to <li>{{ brand.brand_name }}</li>. Thanks to #LinhNguyen for giving me the idea.
You forgot to close your a tag and since you already declared your url name in urls.py so no need to add the app name before the url
{{ brand.brand_name }}

Block in django doesnt show the another views

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.

Categories

Resources