The following error occurs
The 'poster' attribute does not have a file associated with it
I don't quite understand what it may be related to and how to fix it
I tried to change the url value, but nothing worked.
html
<div class="container" style="grid-template-columns: repeat(auto-fill, 300px);">
for serial in serials %}
<div class="item">
<img src="{{ serial.poster.url }}" class="img-fluid" alt="">
<p>
{{ serial.title }}
</p>
</div>
endfor %}
</div>
views.py
class SerialDetailView(View):
def get(self, request):
serials = Serials.objects.all()
genres = Genre.objects.all()
return render(request, "serials/single_serial.html", {"serials": serials, "genres": genres})
urls.py
urlpatterns = [
path('register/', views.Register.as_view(), name='register'),
path('reg/', views.Reg.as_view(), name='reg'),
path("serials_list/", views.SerialsView.as_view(), name='serials_list'),
path("add/", views.AddView.as_view(), name='add'),
path("single_serial/", views.SerialDetailView.as_view(), name='single_serial'),
path("<slug:slug>/", views.SingleSerial.as_view(), name='detail_serial'),
path("actor/<int:id>/", views.ActorView.as_view(), name='actor_detail'),
]
My models
class Serials(models.Model):
title = models.CharField('Name',max_length=100)
description = models.CharField('Description', max_length= 200)
poster = models.ImageField('Poster', upload_to='serials/')
date = models.DateField('Date')
country = models.CharField('Страна',max_length=100)
actors = models.ManyToManyField(Actor, verbose_name='actors', related_name='actor')
genre = models.ManyToManyField(Genre, verbose_name='genres')
category = models.ForeignKey(Category, verbose_name='category', on_delete=models.SET_NULL, null=True)
url = models.SlugField(unique=False)
link = models.URLField(max_length=200, blank=True)
Because you are trying to display the image of one of the serials while you did not choose an image for it.
First, choose an image for all serials poster or use the following code:
<div class="container" style="grid-template-columns: repeat(auto-fill,
300px);">
for serial in serials %}
<div class="item">
{% if serial.poster %}
<img src="{{ serial.poster.url }}" class="img-fluid"
alt="">
{% endif %}
<p>
{{ serial.title }}
</p>
</div>
{% endfor %}
</div>
Related
I am working on a library project that displays books and each both is in a category(history, math, adventure, etc). On the detailed view of a book, I want a link (with "See similar books in this category") that will redirect the user to other books of the same category of the current book. So if the detail page of a book has a category of "history", the link will direct to other books in the "history" category. The redirection is to another template (Addon: In helping me out, I would love to display the "similar books" in the same page, not a different page)
error details
TypeError at /search/similar/bootsrtap/
'Book' object is not iterable
models.py
class Category(models.Model):
name = models.CharField(max_length=255)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('index')
choices = Category.objects.all().values_list('name', 'name')
choice_list = []
for item in choices:
choice_list.append(item)
class Book(models.Model):
title = models.CharField(max_length=255)
author = models.CharField(max_length=255)
category = models.CharField(max_length=255, choices=choice_list)
slug = models.SlugField(max_length=100, unique=True)
def __str__(self):
return self.author + ": " + self.title
def get_absolute_url(self):
return reverse('detail', kwargs={'slug': self.slug})
def save(self, *args, **kwargs):
if not self.slug:
self.slug = slugify(self.title)
return super().save(*args, **kwargs)
def similar_book(self):
return Book.objects.filter(category=self.category)
urls.py
urlpatterns = [
path('detail/<slug:slug>/', BookDetail.as_view(), name='detail'),
path('search/similar/<slug:slug>/', views.search_similar_results, name='search_similar_results'),
views.py
def search_similar_results(request, slug):
books = get_object_or_404(Book, slug=slug)
books.similar_book()
return render(request, 'book/similar_results.html', {'books': books})
class BookDetail(generic.DetailView):
model = Book
context_object_name = 'book'
template_name = 'book/detail.html'
clickable link to lead to the template
Click to see Similar books in this category</h3>
<div class="row">
template
<div class="row">
{% if books %}
{% for book in books %}
<h2>Similar Books in {{ book.category } Category}</h2>
<figure class="col-lg-3 col-md-4 col-sm-6 col-12 tm-gallery-item animated bounce infinite">
<a href="{{ book.get_absolute_url }}">
<div class="tm-gallery-item-overlay">
{% if book.cover %}
<img src="{{ book.cover.url }}" alt="Image" class="img-fluid tm-img-center">
{% endif %}
<p class="small font-italic">Author: {{ book.author }}</p>
<p class="small font-italic text-left">Title: {{ book.title }}</p>
<p class="small font-italic">Category: {{ book.category }}</p>
</div>
</a>
</figure>
{% endfor %}
{% else %}
<p>There are No Available Books</p>
{% endif %}
</div>
details.html
<div class="tm-main-content no-pad-b">
<!-- Book Detail Page Display -->
<section class="row tm-item-preview">
{% if book.cover %}
<div class="col-md-6 col-sm-12 mb-md-0 mb-5">
<img src="{{ book.cover.url }}" alt="Image" class="img-fluid tm-img-center-sm card-img-top">
<h2>Title {{ book.title }}</h2>
</div>
{% else %}
<p>No book cover</p>
{% endif %}
</section>
<!-- Similar Books Display by Category -->
<div class="tm-gallery no-pad-b">
<h3 style="color: white; text-align: center;">Similar books you might be interested in</h3>
<div class="row">
{% for item in similar_book%}
<figure class="col-lg-3 col-md-4 col-sm-6 col-12 tm-gallery-item">
<a href="{{ book.get_absolute_url }}">
<div class="tm-gallery-item-overlay">
<img src="{{ book.cover.url }}" alt="Image" class="img-fluid tm-img-center">
</div>
<p class="tm-figcaption">Title: {{ book.title}}</p>
<p class="tm-figcaption">Category: {{ book.category }}</p>
</a>
</figure>
{% endfor %}
</div>
</div>
</div>
You need to pass the result of the similar books to the template, so:
def search_similar_results(request, slug):
book = get_object_or_404(Book, slug=slug)
books = book.similar_book()
return render(request, 'book/similar_results.html', {'books': books})
In the DetailView, you can pass the `similar books with:
class BookDetail(generic.DetailView):
model = Book
context_object_name = 'book'
template_name = 'book/detail.html'
def similar_books(self):
return self.object.similar_book()
Then in the template we work with:
{% for item in view.similar_books %}
<!-- … -->
{% endfor %}
I'm trying to sort my projects by categories: all, css, HTML, Django, and so on. and also trying to add pagination when showing all projects have a limit of 6 projects per page. I'm stuck and have trouble combining either the pagination work or the filter/ sorting the items work, here's my code. Please Help :)
models.py
class Category (models.Model):
category_name = models.CharField(max_length=150)
slug = models.SlugField(unique=True)
class Meta:
ordering = ('-category_name',)
def __str__(self):
return self.category_name
def get_absolute_url(self):
return reverse('mainpages:project_by_category', args=[self.slug])
class Project(models.Model):
category = models.ForeignKey(Category, on_delete=models.CASCADE, default='', null=True)
title = models.CharField(max_length=100)
description = models.TextField()
technology = models.CharField(max_length=20)
proj_url = models.URLField(max_length=200, blank=True)
blog_link = models.URLField(max_length=200, blank=True)
image = models.ImageField(default='post-img.jpg', upload_to='proj-img')
class Meta:
ordering = ('-title',)
def __str__(self):
return self.title
view.py
def portfolioView(request, category_slug=None):
# added
category = None
categories = Category.objects.all()
# filtering by project
projs = Project.objects.all()
# paginator added
projects = Project.objects.all()
paginator = Paginator(projects, 3)
page = request.GET.get('page')
try:
projects = paginator.page(page)
except PageNotAnInteger:
projects = paginator.page(1)
except EmptyPage:
projects = paginator.page(paginator.num_pages)
# added
if category_slug:
category = get_object_or_404(Category, slug=category_slug)
projs = projs.filter(category=category)
#
return render(request, 'mainpages/portfolio.html', {
'category': category,
'categories': categories,
'projects': projects,
'page': page,
'projs': projs,
})
def projectDetail(request, pk):
project = Project.objects.get(pk=pk)
context = {
'project': project
}
return render(request, 'mainpages/portfolio-detail.html', context)
pagination.html
<div class="pagination">
<span class="step-links">
{% if page.has_previous %}
Previous
{% endif %}
<span class="current">
Page {{ page.number }} of {{ page.paginator.num_pages }}
</span>
{% if page.has_next %}
Next
</span>
{% endif %}
</div>
porftfolio.html
{% extends 'mainpages/base.html' %}
{% load static %}
{% block content %}
<!-- -->
<section class="portfolio-section">
<!-- -->
<div class="portfolio-info">
<h1>PORTFOLIO</h1>
<p>Industry's so electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop</p>
</div>
<!-- -->
<div class="category-container">
<div class="category-wrapper">
<div class="category-title">
<h3>Catergories</h3>
</div>
<!-- -->
<div class="category-links">
<ul>
<li>ALL</li>
{% for c in categories %}
<li>
{{ c.category_name}}
</li>
{% endfor %}
</ul>
</div>
<div>
<h1>
{% if category %}
<p class="center-category">All {{ category.category_name }} Projects</p>
{% else %}
<p class="center-category">All Projects</p>
{% endif %}
</h1>
{% for p in project %}
{{ p.title }}
{% endfor %}
</div>
<!-- -->
</div>
</div>
<div class="work-container">
<div class="work-wrapper">
{% for project in projects %}
<div class="work-links">
<div class="card">
<img class="work-img" src="{{ project.image.url }}" alt="">
<h6 class="title">{{ project.title }}</h6>
<span> {{ project.description |truncatechars:50 }}</span>
<button class="works-btn">
View Project
</button>
</div>
</div>
{% endfor %}
</div>
</div>
{% include 'mainpages/pagination.html' with page=projects %}
</section>
{% endblock %}
I want to assign a task to one of the users who commented on the post. But when I try to go on post_detail.html an error occurs, and i.e.
OperationalError at /home/
no such column: home_post.assign_to_id
PS: I have done python manage.py makemigrations and python manage.py migrate
So, here is the code snippet. I can give more information if needed. Thanks in advance!
views.py
def SaveAssigned(request):
if request.method == "POST":
if request.POST.get('assigned'):
savevalue = Post()
savevalue.assign_to = request.POST.get('assigned')
savevalue.save()
return render(request, 'post_detail.html')
else:
return render(request, 'post_detail.html')
class PostDetailView(DetailView):
model = Post
# template_name = 'home/post_detail.html'
def get_context_data(self, *args, **kwargs):
post_available = get_object_or_404(Post, id=self.kwargs['pk'])
cat_menu = Category.objects.all()
context = super(PostDetailView, self).get_context_data()
context["cat_menu"] = cat_menu
return context
urls.py
urlpatterns = [
path('', PostListView.as_view(), name='home'),
path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'),
path('post/new/', PostCreateView.as_view(), name='post-create'),
path('post/<int:pk>/update/', PostUpdateView.as_view(), name='post-update'),
path('post/<int:pk>/delete/', PostDeleteView.as_view(), name='post-delete'),
path('post/<int:pk>/comment/', AddCommentView.as_view(), name='add-comment'),
path('add_category/', AddCategoryView.as_view(), name='add-category'),
path('category/<str:cats>/', CategoryView, name='category'),
path('category-list/', CategoryListView, name='category-list'),
]
models.py
class Post(models.Model):
title = models.CharField(max_length = 100)
snippet = models.CharField(max_length= 200)
content = RichTextField(blank=True, null=True)
date_posted = models.DateTimeField(default = timezone.now)
author = models.ForeignKey(User, on_delete= models.CASCADE)
category = models.CharField(max_length=255, default='Coding')
assign_to = models.ForeignKey(User,related_name='assign_to', on_delete=models.CASCADE, null=True)
def __str__(self):
return self.title + ' | ' + str(self.author)
def get_absolute_url(self):
return reverse('home')
post_detail.html
{% extends 'users/base.html' %}
{% block body %}
<article class="media content-section">
<img class="rounded-circle article-img" src="{{ object.author.profile.image.url }}">
<div class="media-body">
<div class="article-metadata">
<a class="mr-2" href="#">{{ object.author }}</a>
<small class="text-muted">{{ object.category }}</small>
<small class="text-muted" style="float: right;">{{ object.date_posted|date:"F d, Y" }}</small>
</div>
<h2 class="article-title">{{ object.title }}</h2>
<p class="article-content">{{ object.content|safe }}</p>
</div>
</article>
{% if object.author == user %}
<div>
<a class="btn btn-outline-secondary bt-sm mt-1 mb-1" href="{% url 'post-update' object.id %}">Update</a>
<a class="btn btn-outline-danger bt-sm mt-1 mb-1" href="{% url 'post-delete' object.id %}">Delete</a>
<a class="btn btn-outline-primary bt-sm mt-1 mb-1" style="float: right;" href="">Done</a>
</div>
<form method="POST">
{% csrf_token %}
<select name="assigned">
<option selected disabled="true"> Select User</option>
{% if not post.comments.all %}
<option>NA</option>
{% else %}
{% for comment in post.comments.all %}
<option>{{ comment.author }}</option>
{% endfor %}
{% endif %}
</select>
<input type="submit" value="Assign" name="">
</form>
{% endif %}
<br>
<hr>
<h2>Comment Section</h2>
<br>
{% if not post.comments.all %}
No Comments yet
<br>
Be the first Ont to Comment!
{% else %}
Add a comment
<br>
{% for comment in post.comments.all %}
<strong>
{{ comment.author }} - {{ comment.date_added }}
</strong>
<br>
{{ comment.body }}
<br><br>
{% endfor %}
<hr>
{% endif %}
<br><br>
{% endblock %}
This error occurs when your model does not contain the specific column and you are trying to add the value in that model with a specific column name.
You can solve this by following steps -
Step - 1. python manage.py makemigration
Step - 2. python manage.py migrate
well, I am a beginner but a mid-level beginner and I am building an e-commerce website. I have vendor, customer and products which relate to a specific vendor. I have made a view to display the all kind of products on the page and I have also parsed the Vendor model in products view. but I am getting all vendors on a single product which shows that code is not working well as it should have. I hope you guys got the point what I want to ask?
for convenience here is the code.
views.py:
def products(request):
vendor = Vendor.objects.all()
products_list = Item.objects.all()
context = {
'vendors': vendor,
'products': products_list,
}
template = 'vstore/products.html'
return render(request, template, context)
products.html:
<div class="row">
{% for item in products %}
<div class="col-3">
<div class="item">
<div class="strip">
<figure>
{% if item.discount >= 20 %}
<span class="ribbon off">{{item.discount}}% OFF</span>
<a href="{% url 'product_detail_view' item.pk %}" class="strip_info">
<img class="" src="{{ item.image.url }}" alt="Vendor's Photo">
</a>
{% else %}
<a href="{% url 'product_detail_view' item.pk %}" class="strip_info">
<img class="" src="{{ item.image.url }}" alt="Vendor's Photo">
</a>
{% endif %}
</figure>
<ul>
<li><span class="loc_open">{{ item.name }}</span></li>
<li>
<div class="score "><div class="score "><span class="">{% for vendor in vendors %}{{vendor.name}}{% endfor %}<h5><div class="item_title"><small>AED {{item.price}}</small></div></h5></span><strong>C</strong></div></div>
</li>
</ul>
</div>
</div>
</div>
{% endfor %}
</div>
my models.py:
class Vendor(models.Model): # this is to create a new model for restaurant
user = models.OneToOneField(User, on_delete=models.CASCADE,
related_name='vstore') # OneToOneField is to ensure that one user have only one restarant.
name = models.CharField(max_length=500)
phone = models.CharField(max_length=500)
address = models.CharField(max_length=500)
logo = models.ImageField(upload_to='vstore_logo/', blank=False)
def __str__(self):
return self.name
class Item(models.Model):
vstore = models.ForeignKey(Vendor, on_delete=models.CASCADE)
category = models.ForeignKey(Categories, on_delete=models.CASCADE)
childcategory = models.ForeignKey(ChildCategories, on_delete=models.CASCADE)
subchildcategory = models.ForeignKey(SubChildCategories, on_delete=models.CASCADE)
name = models.CharField(max_length=500)
short_description = models.CharField(max_length=82)
image = models.ImageField(upload_to='Sheesha_images/', blank=False)
price = models.IntegerField(default=0)
discount = models.IntegerField(default=0, null=True, blank=True)
long_description = models.TextField(max_length=500, null=True, blank=True)
weight = models.IntegerField(null=True, blank=True)
size = models.IntegerField(null=True, blank=True)
base = models.IntegerField(null=True, blank=True)
quantity = models.IntegerField(default=1)
def __str__(self):
return self.name
You can access the vendor object related to that item {{item.vstore.name}}. So I think it will work if you update your code like this;
<div class="row">
{% for item in products %}
<div class="col-3">
<div class="item">
<div class="strip">
<figure>
{% if item.discount >= 20 %}
<span class="ribbon off">{{item.discount}}% OFF</span>
<a href="{% url 'product_detail_view' item.pk %}" class="strip_info">
<img class="" src="{{ item.image.url }}" alt="Vendor's Photo">
</a>
{% else %}
<a href="{% url 'product_detail_view' item.pk %}" class="strip_info">
<img class="" src="{{ item.image.url }}" alt="Vendor's Photo">
</a>
{% endif %}
</figure>
<ul>
<li><span class="loc_open">{{ item.name }}</span></li>
<li>
<div class="score "><div class="score "><span class="">{{item.vstore.name}}<h5><div class="item_title"><small>AED {{item.price}}</small></div></h5></span><strong>C</strong></div></div>
</li>
</ul>
</div>
</div>
</div>
{% endfor %}
</div>
my model:
class News(models.Model):
CATEGORY=(("0","Politics"),("1","Sports"),("2","Health"),("3","Business"),("4","International"),("5","Finance"))
title=models.CharField(max_length=250)
story= models.TextField()
count= models.IntegerField(default=0)
like = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True , related_name='post_likes')
video_url = models.URLField(max_length=270,null=True,blank=True) #makemigrations garna baki xa
category= models.CharField(choices=CATEGORY, max_length=2)
slug=models.SlugField(max_length=270,blank=True,null=True)
created_at=models.DateTimeField(auto_now_add=True)
updated_at=models.DateTimeField(auto_now=True)
cover_image=models.ImageField(upload_to="uploads")
author= models.CharField(max_length=100,null=True)
video_image = models.ImageField(upload_to="uploads",blank=True,null=True)
video_title = models.CharField(max_length=250,blank=True,null=True)
my view:
class NewsTemplateView(TemplateView):
template_name="index.html"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
news=News.objects.all()
context["latest_news"] = news.order_by("-created_at") [:4]
context["breaking_news"] = news.filter(Q(category="0")|Q(category="1")).order_by("-created_at") [:3]
context["political_news"] = news.filter(category="0").order_by("-created_at") [:4]
context["sports_news"] = news.filter(category="1").order_by("-created_at") [:4]
context["health_news"] = news.filter(category="2").order_by("-created_at") [:4]
context["business_news"] = news.filter(category="3").order_by("-created_at") [:4]
context["international_news"] = news.filter(category="4").order_by("-created_at") [:4]
context["finance_news"] = news.filter(category="5").order_by("-created_at") [:4]
context["video_news"] = news.order_by("-created_at") [:3]
context["popular_news"] = news.order_by("-count")[:6]
return context
my template:
<!-- Single Video Post -->
{% for news in video_news %}
<div class="col-12 col-sm-6 col-md-4">
<div class="single-video-post">
<img src="{{ news.video_image.url }}" alt="">
<!-- Video Button -->
<div class="videobtn">
<i class="fa fa-play" aria-hidden="true"></i>
</div>
</div>
</div>
{% endfor %}
As the error states, there is probably a News object that has no file associated with it. Either make it mandatory by setting blank and null to False:
video_image = models.ImageField(upload_to="uploads",blank=False ,null=False)
Or check if the image is set before accessing its url by changing:
<img src="{{ news.video_image.url }}" alt="">
to:
{% if news.video_image %}
<img src="{{ news.video_image.url }}" alt="">
{% endif %}
You can even display some kind of placeholder image, or some text with:
{% if news.video_image %}
<img src="{{ news.video_image.url }}" alt="">
{% else %}
<img src="link/to/some/placeholder.jpg"
{% endif %}