Unable to render images in caraousel from database in django? - python

I am trying to render images from my database to carousel in Django. I have a model which contains url fields to store images url but when I use them in (template.html) my carousel img src, it only renders 1st image but not others even though I have three images url stored in database. To understand it better here is my code.
models.py
from django.db import models
# Create your models here.
class CaraouselData(models.Model):
title = models.CharField(max_length=100, null=False)
description = models.TextField(max_length=200, null=True)
image = models.URLField(null = False, default=True)
def __str__(self):
return self.title
views.py
def home(request):
caraousel_data = CaraouselData.objects.all()
return render(request, 'index.html', context={
'caraousel_data': caraousel_data,
})
template.js
{% block content %}
{# Caraousel Data Section#}
<div class="container-fluid p-0">
<div id="carouselExampleCaptions" class="carousel slide" data-bs-ride="carousel">
<div class="carousel-indicators">
<button type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide-to="0" class="active" aria-current="true" aria-label="Slide 1"></button>
<button type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide-to="1" aria-label="Slide 2"></button>
<button type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide-to="2" aria-label="Slide 3"></button>
</div>
{# images fetching from models #}
<div class="carousel-inner">
{% for item in caraousel_data %}
<div class="carousel-item {% if forloop.counter0 == 0 %} active" {% endif %}>
<img src="{{ item.image }}" width="600" height="670" class="d-block w-100" alt="...">
<div class="carousel-caption d-none d-md-block">
<h5>{{ item.title }}</h5>
<p>{{ item.description }}</p>
</div>
</div>
{% endfor %}
{% endblock %}

I think you have not installed the pillow library.🤔
To handle images you must install them first.

Related

How to write an image attribute file in django (The 'image' attribute has no file associated with it)

I am building a django blog website and I am trying to upload an image on the website. I can access the photos on the admin page but whenever I try to access it on the page I get an enroll. The trace back says
"
The 'image' attribute has no file associated with it.
This my code for the model
class article(models.Model):
title = models.CharField(max_length=200)
author = models.ForeignKey(User, on_delete=models.CASCADE)
content = models.TextField()
image = models.ImageField(null=True, blank=True, upload_to='static/media/article')
date = models.DateTimeField(default=timezone.now)
def __str__ (self):
return self.title
def get_absolute_url(self):
return reverse('article-detail', kwargs= {'pk':self.pk})
This is my views code
class ArticleCreateView(LoginRequiredMixin, CreateView):
model = article
fields= ['title', 'content', 'image']
def ArticleCreateView(request):
if request.method == "POST":
form = ArticleForm(request.POST, request.FILES)
if form.is_valid():
article = form.save(commit=False)
article.author = request.user.id
article.save()
return HttpResponse
this is the blog template code
{% extends "agri_tourism/base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<section class="flex-container">
<div>
{% for article in articles %}
<article class="media content-section">
{% load static %}
<div class="media-body">
<div style="text-decoration:none; display: inline-block;" class="article-metadata">
<img class="rounded-circle article-img" src="{{user.profile.image.url}}">
<a style="text-decoration:none;" class="mr-2" href="#">{{ article.author }}</a>
<small class="article-date">{{ article.date|date:"F d, Y" }}</small>
</div>
<h2><a class="article-title" href="">{{ article.title }}</a></h2>
<p class="article-content">{{ article.content }}</p>
<img class="image-content" id="image-el" src = "{{article.image.url}}">
<div class="like-share-btns">
</div>
</article>
{% endfor %}
The form page code is below
{% extends "agri_tourism/base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<div class = "content-section">
<div class = "container">
<div class = "row md-8">
<form method = "POST" enctype="multipart/form-data">
{% csrf_token %}
<fieldset class = "form-group">
<legend class ="border-bottom mb-4">Blog article</legend>
{{form|crispy }}
{{form.media}}
</fieldset>
<div class= "form-group">
<button class="btn btn-outline-info" type="submit" style= "margin-top:4px; ">Submit the Article</button>
</div>
</form>
</div>
</div>
</div>
I want to access photos on the blog page
check the image with if condition like this...
<div class="media-body">
<div style="text-decoration:none; display: inline-block;" class="article-metadata">
{% if user.profile.image.url %}
<img class="rounded-circle article-img" src="{{user.profile.image.url}}">
{% endif %}
<a style="text-decoration:none;" class="mr-2" href="#">{{ article.author }}</a>
<small class="article-date">{{ article.date|date:"F d, Y" }}</small>
</div>
and also check those settings
urls.py (in project directory)
from django.conf import settings # --------> this
from django.conf.urls.static import static # --------> this
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('myapp.urls')),
]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # --------> this
settings.py (in project directory)
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

How to use conditional on Django template?

Im working on my django project. The home page of my project is to show all of my post and category-based post on the bottom after the first part. But my code isnt working and i dont know why. Please help me, im a django noob
#the word Opini is one of my post category
{% for post in blog_posts %}
<div class="card d-inline-flex m-1" style="width: 18rem;">
<a href="{% url 'post-detail' post.pk %}" >
<img class="card-img-top postimg" src="{{ post.post_img.url }}" alt="Card image cap">
</a>
<h3>{{post.category}}</h3>
<div class="card-body">
<h5 class="card-text text-center">{{ post.post_title }}</h5>
<p class="card-text">{{post.post_content|truncatechars:75|safe }}</p>
</div>
</div>
{% endfor %}
<h1> Opini </h1>
{% for post in blog_posts %}
{% if post.category == "Opini" %}
<div class="card d-inline-flex m-1" style="width: 18rem;">
<a href="{% url 'post-detail' post.pk %}" >
<img class="card-img-top postimg" src="{{ post.post_img.url }}" alt="Card image cap">
</a>
<h3>{{post.category}}</h3>
<div class="card-body">
<h5 class="card-text text-center">{{ post.post_title }}</h5>
<p class="card-text">{{post.post_content|truncatechars:75|safe }}</p>
</div>
</div>
{% endif %}
{% endfor %}
{% endfor %}
My Models
class Category(models.Model):
name = models.CharField(max_length=100, unique=True)
class Meta:
verbose_name_plural = "Categories"
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('post_by_category', args=[self.name])
class Post(models.Model):
post_title = models.CharField(max_length=50)
post_img = models.ImageField(upload_to='postImage/')
post_content = RichTextField(blank= True, null = True)
category = models.ForeignKey(Category , on_delete=models.CASCADE)
post_date = models.DateTimeField(auto_now_add=True)
post_author = models.ForeignKey(User, on_delete=models.CASCADE)
class Meta:
ordering = ["-post_date"]
def __str__(self):
return f'{self.post_title}'
When i run the code, only the first page works, when it comes to the second part, nothing appeared
If "Opini" is the category name then you should compare it like this:
{% if post.category.name == "Opini" %}

Django Custom Tag Problems

Hello Stack Overflow !
I am making a news site in Django as a part of my "internship", I have just started learning web development. I was given a task to make a custom template ( it HAS to be a custom template ) which will render out 3 latest news from a category, and I have to include it as a sidebar on my "article" page.
I tried to write the custom tag, but it's not going to well unfortunately. This is my "last" task for the website, and I'm stuck (like many times before :P )
Here's the thing..everything is working if I include the custom tag on my "list all articles" page, it renders correctly depending on which category I click on.
The thing is, once I try to include my tag into my "single article" page I hit a brick wall. The tag is still working, but is now displaying all of my articles, instead of filtering the articles related to that article's category.
To simplyfiy, If i click on a "health" article to open it, I want the sidebar just to include the articles for the "health" category, I hope that makes sense.
Anyone with a couple of minutes of spare time willing to help me out ? :)
My code :
the custom tag:
from django import template
from news.models import Article
register = template.Library()
#register.inclusion_tag("news/categories.html")
def show_results(article):
article = article.filter()[:3]
return {'article': article}
HTML template for the tag:
{% load article_extras %}
<div class="articles-filter">
<ul>
{% for a in article %}
<img src="{{ a.article_image.url }}" alt="">
<h5>{{ a.title }}</h5>
{% endfor %}
</ul>
</div>
my models :
from django.db import models
from datetime import datetime
from autoslug import AutoSlugField
class Category(models.Model):
category_title = models.CharField(max_length=200, default="")
def __str__(self):
return self.category_title
class Article(models.Model):
title = models.CharField('title', max_length=200, blank=True)
slug = AutoSlugField(populate_from='title', default="",
always_update=True, unique=True)
author = models.CharField('Author', max_length=200, default="")
description = models.TextField('Description', default="")
is_published = models.BooleanField(default=False)
article_text = models.TextField('Article text', default="")
pub_date = models.DateTimeField(default=datetime.now, blank=True)
article_image = models.ImageField('Article Image')
article_category = models.ForeignKey(Category, on_delete="models.CASCADE", default="")
img2 = models.ImageField('Article Image 2', default="", blank=True)
img3 = models.ImageField('Article Image 3', default="", blank=True)
img4 = models.ImageField('Article Image 4', default="", blank=True)
img5 = models.ImageField('Article Image 5', default="", blank=True)
img6 = models.ImageField('Article Image 6', default="", blank=True)
def __str__(self):
return self.title
class Comment(models.Model):
post = models.ForeignKey('Article', on_delete=models.CASCADE, related_name='comments')
author = models.CharField(max_length=200)
text = models.TextField()
created_date = models.DateTimeField(default=datetime.now, blank=True)
approved_comment = models.BooleanField(default=False)
def approve(self):
self.approved_comment = True
self.save()
def __str__(self):
return self.text
the "single article" template where I am trying to include my custom tag:
{% extends "news-base.html" %}
{% load static %}
{% load article_extras %}
{% block article %}
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<div class="preloader d-flex align-items-center justify-content-center">
<div class="spinner">
<div class="double-bounce1"></div>
<div class="double-bounce2"></div>
</div>
</div>
{% show_results article %}
<!-- ##### Post Details Area Start ##### -->
<section class="container post-details-area">
<div class="container single-article-div">
<hr class="hr-single">
<h2 class="single-article-titles">{{ article.title }}</h2>
<hr class="hr-single">
<img class="single-article-img" src="{{ article.article_image.url }}" alt="">
<!-- *********************************** -->
<hr class="hr-single">
<p>Category: {{ article.article_category }}</p>
<hr class="hr-single">
<div class="row justify-content-center">
<!-- Post Details Content Area -->
<div class="col-12 col-xl-8">
<div class="post-details-content bg-white box-shadow">
<div class="blog-thumb">
</div>
<div class="blog-content">
<div class="post-meta">
{{ article.pub_date }}
</div>
<h3 class="single-article-titles post-title"> {{ article.description }}</h3>
<hr>
<!-- Post Meta -->
<div class="post-meta-2">
<i class="fa fa-eye" aria-hidden="true"></i> 1034
<i class="fa fa-thumbs-o-up" aria-hidden="true"></i> 834
<i class="fa fa-comments-o" aria-hidden="true"></i> 234
</div>
<p>{{ article.article_text }}</p>
<hr />
{% include "partials/_thumbnails.html" %}
<hr>
<p>Author: {{ article.author }}</p>
<hr>
{% for comment in article.comments.all %}
<div class="comment">
<div class="date">{{ comment.created_date }}</div>
<strong>{{ comment.author }}</strong>
<p>{{ comment.text|linebreaks }}</p>
</div>
{% empty %}
<p>No comments here yet :(</p>
{% endfor %}
</div>
<!-- Post A Comment Area -->
<div class="post-a-comment-area bg-white mb-30 p-30 box-shadow clearfix">
<!-- Section Title -->
<div class="section-heading">
<h5>LEAVE A REPLY</h5>
</div>
<!-- Reply Form -->
<div class="contact-form-area">
<form action="#" method="post">
<div class="row">
<div class="col-12 col-lg-6">
<input type="text" class="form-control comment-section" id="name" placeholder="Your Name*"
required />
</div>
<div class="col-12 col-lg-6">
<input type="email" class="form-control comment-section" id="email" placeholder="Your Email*"
required />
</div>
<div class="col-12">
<textarea name="message" class="form-control" id="message" cols="30" rows="10"
placeholder="Message*" required></textarea>
</div>
<div class="col-12">
<button class="btn mag-btn comment-section" type="submit">
Submit Comment
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
{% endblock %}
my views.py:
from django.shortcuts import render, reverse, get_object_or_404
from django.views import generic
from news.models import Article, Category
from .forms import CommentForm
from django.http import HttpResponseRedirect
class IndexView(generic.ListView):
template_name = 'news/index.html'
context_object_name = 'latest_article_list'
def get_queryset(self):
return Article.objects.order_by("-pub_date").filter(is_published=True)[:6]
class CategoryView(generic.ListView):
template_name = 'news/categories.html'
context_object_name = 'category'
def get_queryset(self):
return Article.objects.filter(article_category__category_title="Politics")
class ArticlesView(generic.ListView):
context_object_name = 'latest_article_list'
template_name = 'news/articles.html'
paginate_by = 5
def get_context_data(self, **kwargs):
context = super(ArticlesView, self).get_context_data(**kwargs)
context['categories'] = Category.objects.all()
return context
def get_queryset(self):
category_pk = self.request.GET.get('pk', None)
if category_pk:
return Article.objects.filter(article_category__pk=category_pk).order_by("-pub_date")
return Article.objects.order_by("-pub_date")
def article(request, article_id):
article = get_object_or_404(Article, pk=article_id)
context = {'article': article}
return render(request, 'news/article.html', context)
def add_comment_to_article(request, pk):
article = get_object_or_404(Article, pk=pk)
if request.method == "POST":
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.post = article
comment.save()
return HttpResponseRedirect(reverse('news:article', kwargs={"article_id": article.pk}))
else:
form = CommentForm()
return render(request, 'news/add_comment_to_article.html', {'form': form})
my "all articles" page:
<div class="container">
{% block articles %}
<!-- ***************************************** -->
<div class="category-filter container">
<ul>
<li class="categories-title">Categories:</li>
<hr class="small-line">
{% for category in categories %}
<li class="category-list">
{{ category.category_title }}
</li>
{% endfor %}
</ul>
</div>
<!-- ***************************************** -->
{% show_results latest_article_list %}
<hr class="hr-style1">
<h2 class="article-list-title">Article List :</h2>
<hr class="hr-style2">
<div class="container list-wrapper">
{% for article in latest_article_list %}
<div class="container">
<div class="well">
<div class="media">
<a class="pull-left" href="{% url 'news:article' article.id %}">
<img class="media-object" src="{{ article.article_image.url }}">
</a>
<div class="media-body">
<h4 class="media-heading">{{ article.title }}
</h4>
<p class="text-right">{{ article.author }}</p>
<p>{{ article.description }}</p>
<ul class="list-inline list-unstyled">
<li><span><i class="glyphicon glyphicon-calendar"></i> {{ article.pub_date }}
</span></li>
<li>|</li>
<span><i class="glyphicon glyphicon-comment"></i> 2 comments</span>
<li>|</li>
<li>
<span class="glyphicon glyphicon-star"></span>
<span class="glyphicon glyphicon-star"></span>
<span class="glyphicon glyphicon-star"></span>
<span class="glyphicon glyphicon-star"></span>
<span class="glyphicon glyphicon-star-empty"></span>
</li>
<li>|</li>
<li>
<span><i class="fa fa-facebook-square"></i></span>
<span><i class="fa fa-twitter-square"></i></span>
<span><i class="fa fa-google-plus-square"></i></span>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
{% endfor %}
Thank you so much for taking the time to read this.
Have a good day !
Your changed code wouldn't work at all on the single article page; you would get an AttributeError.
The problem is that you are in your list view you are passing the queryset, latest_article_list, but in the single article view you are passing that single article. You can't filter an article, you can only filter a queryset.
Really it seems that the thing you want to do is to pass a category. There's no reason to pass the latest article list to that template tag; you can just get the articles directly in the tag. But from the single article view you want to get the articles with the same category. So, make the parameter category, and make it optional.
#register.inclusion_tag("news/categories.html")
def show_results(category=None):
articles = Article.objects.all()
if category:
articles = articles.filter(category=category)
return {'article': article[:3]}
Now from the list view you can just call the tag without arguments:
{% show_results %}
whereas from the single view you can pass the article category:
{% show_results article.category %}

Django Field is showing up in one view but not the other

I'm just starting out with Django and I have a problem where, when I added a field to my model (JobPost which inherits from models.Model) and it migrated successfully I can see and interact with the new field when I create a job post, but not when I view the JobPost (which is displayed using crispy forms using the {{ form|crispy }} tag.
I have added the field name to my fields = [''] in my views.py
models.py
class JobPost(models.Model):
#constants
CLEARANCE_LEVELS=[(...),]
author = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=100)
content = models.TextField()
clearance_required = models.CharField(max_length=50, choices=CLEARANCE_LEVELS, default='None')
date_posted = models.DateTimeField(default=timezone.now)
views.py
class JobDetailView(DetailView):
model = JobPost
class JobCreateView(LoginRequiredMixin, CreateView):
model = JobPost
fields = ['title', 'content', 'clearance_required']
# form_valid checks if the user is logged in
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
jobpost_form.html
{% load crispy_forms_tags %}
{% block content %}
<div class="content-section">
<form method="POST">
{% csrf_token %} <!--Used to prevent some XSS Attacks (Cross-site request forgery) -->
<fieldset class="form-group">
<legend class="border-bottom mb-4">Create Job Post</legend>
{{ form|crispy }}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Submit</button>
</div>
</form>
</div>
{% endblock content %}
jobpost_detail.html
{% block content %}
<article class="media content-section">
<img class="rounded-circle article-img" src="{{ object.author.profile.image.url }}">
<div class="media-body">
<div class="mb-2 article-metadata">
<a class="mr-1" href="{% url 'profile' %}">{{ object.author }}</a> <!-- BROKEN LINK: SIMPLY TAKES TO CURRENTLY LOGGED IN USER-->
<small class="text-muted">{{ object.date_posted|date:"F d, Y" }}</small>
{% if object.author != user %}
<a class="btn btn-secondary btn-sm float-right" href="{% url 'user-jobs' object.author.username %}">See all jobs the user applied to</a>
{% endif %}
<div>
{% if object.author == user %}
<a class="btn btn-secondary btn-sm mt-1 mb-1 float-right" href="{% url 'user-jobs' object.author.username %}">See all jobs the user applied to</a>
<a class="btn btn-secondary btn-sm mt-1 mb-1" href="{% url 'job-update' object.id %}">Update Job Posting</a>
<a class="btn btn-danger btn-sm mt-1 mb-1" href="{% url 'job-delete' object.id %}">Delete</a>
{% endif %}
</div>
</div>
<div class="mt-1">
<h2 class="article-title">{{ object.title }}</h2>
<p class="article-content">{{ object.content }}</p>
</div>
</div>
</article>
{% endblock content %}
So when I view it in my browser, I see the "clearance_required" field when I create a job post. But when I just view the job post, it only shows the title and description, not the new clearance_required field. I don't know how I can get it to display.
Here's a picture of the issue:
Notice how the clearance field is missing in the second picture
Do you actually output in object.clearance_required in jobpost_detail.html, because I cannot see it?
And by the way, if you output it, you should use object.get_clearance_required_display, because it is a field with choices.

i am getting an error saying category matching query does not exist

The voting proceess is working fine with this code. The problem is only when redirecting after voting the options.
Exception Type:DoesNotExist
Exception Value:
Category matching query does not exist.
category = Category.objects.get(slug=slug)
urls.py
path('<slug>/',views.options,name='options'),
path('<slug>/vote/', views.vote, name='vote'),
views.py
def home(request):
categories = Category.objects.filter(active=True)
return render(request,'rank/base.html',{'categories': categories,'title':'TheRanker'})
def options(request,slug):
category = Category.objects.get(slug=slug)
options = Option.objects.filter(category=category)
return render(request,'rank/options.html',{'options':options,'title':'options'})
def vote(request,slug):
option = Option.objects.get(slug=slug)
if Vote.objects.filter(slug=slug,voter_id=request.user.id).exists():
messages.error(request,'You Already Voted!')
return redirect('rank:options',slug)
else:
option.votes += 1
option.save()
voter = Vote(voter=request.user,option=option)
voter.save()
messages.success(request,'Voted!')
return redirect('rank:options',slug)
options.html
{% extends "rank/base.html" %}
<title>{% block title %}{{title}}{% endblock title%}</title>
{% load bootstrap4 %}
{% block content %}
<center><br>
<center>{% bootstrap_messages %}</center>
<ol type="1">
{% for option in options %}
<div class="col-lg-6 col-md-6 mb-6">
<div class="card h-100">
<div class="card-body">
<b><li>
<img src="/media/{{option.image}}" width="200" height="100">
<h4>{{option.name}}
</h4>
<h5 class="card-text">{{ option.details}}</h5>
<h5>{{ option.votes }} votes</h5>
<form action="{% url 'rank:vote' option.slug %}" method="post">
{% csrf_token %}
<input type="submit" class="btn btn-success" value="Vote" >
</form>
</li></b>
</div>
<div class="card-footer">
<small class="text-muted"></small>
</div>
</div>
</div>
{% endfor %}
</ol>
</center>
{% endblock content%}
You're confusing categories and options. The form sends the slug of the option, but then you redirect to the categories view using the same slug. But those are two different models.

Categories