I'm trying to create a Carousel that shows multiple pictures of a single cat for a cattery project I'm doing. I'm trying to figure out the right template to make this work.
My Models
class Cat(models.Model):
name = models.CharField(max_length=32, null=True)
available = models.BooleanField()
main_image = models.ImageField(upload_to="images/")
age = models.CharField(max_length=64, null=True)
mix = models.CharField(max_length=128, null=True)
dob = models.CharField(max_length=16)
sex = models.CharField(max_length=16)
description = models.TextField(max_length=256, null=True)
def __str__(self):
return f"{self.name} : {self.sex} {self.age} || Available : {self.available}"
class Images(models.Model):
name = models.CharField(max_length=64, null=True)
image = models.ForeignKey(Cat, related_name='images', on_delete=models.CASCADE)
def __str__(self):
return self.name
My View
def available(request):
context = {}
return render(request, "cattery/available.html", {'available_kittens': Cat.objects.exclude(available=False).all()})
My HTML
{% for kitten in available_kittens %}
<div class="flexbox-item">
<img class="thumbnail" src="{{ kitten.images.url }}">
<h2> {{ kitten.name }} </h2>
<hr>
<h4> {{ kitten.sex }} </h4>
<h6> {{ kitten.dob }} </h6>
<p> {{ kitten.description}} </p>
</div>
{% endfor %}
My Assumption
<div id="carousel" class="carousel slide" data-ride="carousel">
<ol class="carousel-indicators">
<li data-target="#carouselExampleIndicators" data-slide-to="0" class="active"></li>
<li data-target="#carouselExampleIndicators" data-slide-to="1"></li>
<li data-target="#carouselExampleIndicators" data-slide-to="2"></li>
</ol>
<div class="carousel-inner">
{% for image in kitten.images.all() %}
<div class="carousel-item active">
<img class="d-block w-100" src="{{ image }}" alt="First slide">
</div>
{% endfor %}
<div class="carousel-item">
<img class="d-block w-100" src="..." alt="Second slide">
</div>
How can I call the images related to each kitten with a django Template?
I know I could just include multiple image fields, but I've seen people suggest this method of creating a secondary class.
Related
i'm trying to display the news on my website but for some reason its not showing, the first loop is ok, but the second one is not displaying anything where it suposed to be.
Here are my code:
HTML:
<div class="container-fluid">
<div class="container">
<div class="row">
{% for cat in cats %}
<div class="col-lg-6 py-3">
<div class="bg-light py-2 px-4 mb-3">
<h3 class="m-0">{{cat.category_name}}</h3>
</div>
<div class="owl-carousel owl-carousel-3 carousel-item-2 position-relative">
{% for news in category.news_set.all %}
{% if forloop.counter == 4 %}
<div class="position-relative">
<img class="img-fluid w-100" src="{{news.cover.url}}" style="object-fit: cover;">
<div class="overlay position-relative bg-light">
<div class="mb-2" style="font-size: 13px;">
{{news.title}}
<span class="px-1">/</span>
<span>{{news.created_at}}</span>
</div>
<a class="h4 m-0" href="">{{news.description}}</a>
</div>
</div>
{% endif %}
{% endfor %}
</div>
</div>
{% endfor %}
</div>
</div>
views.py:
def home (request):
cats = Category.objects.all()[0:4]
articles = Article.objects.all()
return render (request,'pages/home.html',
context={
'articles': articles,
'cats': cats,
})
models.py
class Category(models.Model):
category_name = models.CharField(max_length=65)
slug = models.SlugField(unique=True)
class Article(models.Model):
title = models.CharField(max_length=65)
description = models.CharField(max_length=165)
slug = models.SlugField(unique=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
is_published = models.BooleanField(default=False)
cover = models.ImageField(
upload_to='newsroom/covers/%Y/%m/%d/', blank=True, default='')
category = models.ForeignKey(
Category, on_delete=models.SET_NULL, null=True, blank=True,
default=None,)
<div class="owl-carousel owl-carousel-3 carousel-item-2 position-relative">
{% for news in cat.news_set.all %}
{% if forloop.counter == 4 %}
<div class="position-relative">
<img class="img-fluid w-100" src="{{news.cover.url}}" style="object-fit: cover;">
<div class="overlay position-relative bg-light">
<div class="mb-2" style="font-size: 13px;">
{{news.title}}
<span class="px-1">/</span>
<span>{{news.created_at}}</span>
</div>
<a class="h4 m-0" href="">{{news.description}}</a>
</div>
</div>
I am assuming that news is a relationship to category.
I've been trying to show some data in my index.html template with no luck.
models.py
class Appartement(models.Model):
nom = models.CharField(max_length=200)
Ville_et_adresse = models.CharField(max_length=200)
NB_de_chambre = models.DecimalField(max_digits=20, decimal_places=0)
NB_de_douche = models.DecimalField(max_digits=20, decimal_places=0)
NB_de_garage = models.DecimalField(max_digits=20, decimal_places=0)
NB_de_piscine = models.DecimalField(max_digits=20, decimal_places=0)
NB_de_cuisine = models.DecimalField(max_digits=20, decimal_places=0)
Superficie = models.DecimalField(max_digits=20, decimal_places=0)
Prix = models.DecimalField(max_digits=20, decimal_places=0)
Description = models.TextField(max_length=1000, default=True)
image = models.ImageField(upload_to="static/upload/", blank=True, null=True)
actif = models.BooleanField(default=True)
def __str__(self):
return f'{self.name}'
class Meta:
ordering = ['-id']
verbose_name_plural =("Appartements")
views.py
from .models import Appartement
def index(request):
appartement = Appartement.objects.all()
context={'appartement':appartement}
return render(request, 'index.html' , context)
index.html
<div class="property-item">
<a class="property-img" href="avendre">
<img src="{% static 'images/property/property_1.jpg'%}" alt="#">
</a>
...
</div>
{% for appartement in Appartement %}
<div class="property-title-box">
<h4>{{ appartement.nom }}</h4>
<div class="property-location">
<i class="fa fa-map-marker-alt"></i>
<p>{{ Appartement.Ville_et_adresse}}</p>
</div>
<ul class="property-feature">
<li> <i class="fas fa-bed"></i>
<span>{{ Appartement.NB_de_chambre }}</span>
</li>
<li> <i class="fas fa-bath"></i>
<span>{{ Appartement.NB_de_douche }}</span>
</li>
<li> <i class="fas fa-arrows-alt"></i>
<span>{{ Appartement.Superficie }}</span>
</li>
<li> <i class="fas fa-car"></i>
<span>{{Appartement.NB_de_piscine }}</span>
</li>
</ul>
<div class="trending-bottom">
<a class="trend-left float-left">
<div class="trend-open">
<p>{{ Appartement.Prix }}</p>
</div>
</a>
</div>
</div>
{% endfor %}
I use django-4 with bootstrap
In your views you are sending all the objects in the context variable appartement. In the template you have used Appartement. Change this to
{% for appt in appartement %}
or change the context variable to appartements such that context={'appartements':appartement}, and then use in your template
{% for appartement in appartements %}
Then inside the for loop access each of the appartement instance like {{appartement.nom}} and so on.
Basically I have three models
class category(models.Model):
name = models.CharField(max_length=40)
class subCategory(models.Model):
category = models.ForeignKey(category, on_delete= models.CASCADE)
name = models.CharField(max_length=40)
class product(models.Model):
name = models.CharField(max_length= 40)
image = models.ImageField(upload_to="media/upload_to")
price = models.DecimalField(max_digits=10, decimal_places= 3)
price_off = models.DecimalField(max_digits=10, decimal_places=3)
description = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
category = models.ForeignKey(category, on_delete= models.CASCADE)
sub_category = models.ForeignKey(subCategory, on_delete= models.CASCADE)
These are the models that I have worked on Now I have to apply ajax on my given template so I don't know how to start There is my image
When I clicked on Samsung then Samsungs product will show and as well others This is my index.html
<div id="mobile-list" class="section-container bg-silver p-t-0">
<!-- BEGIN container -->
<div class="container">
<!-- BEGIN section-title -->
<h4 class="section-title clearfix">
SHOW ALL
Mobile Phones
<small>Shop and get your favourite phone at amazing prices!</small>
</h4>
<!-- END section-title -->
<!-- BEGIN category-container -->
<div class="category-container">
<!-- BEGIN category-sidebar -->
<div class="category-sidebar">
<ul class="category-list">
{% for data in mc %}
<li class="hit" name="{{ data.name }}" data-name="{{ data.name }}"> {{data.name}}</li>
{% endfor %}
</ul>
</div>
<div class="category-detail">
<!-- BEGIN category-item -->
<a href="#" class="category-item full">
<div class="item">
{% for data in mobilePhone %}
{% if forloop.counter == 1 %}
<div class="item-cover">
<img src="{{data.image.url}}" alt="" />
</div>
<div class="item-info bottom">
<h4 class="item-title">{{data.name}}</h4>
<p class="item-desc">{{data.description}}</p>
<div class="item-price"> {{data.price}}</div>
</div>
{% endif %}
{% endfor %}
</div>
</a>
<!-- END category-item -->
<!-- BEGIN category-item -->
<div class="category-item list">
<!-- BEGIN item-row -->
<div class="item-row">
<!-- BEGIN item -->
<div id = "ididid">
{% for data in mobilePhone %}
{% if forloop.counter > 1 %}
<div class="item item-thumbnail">
<a href="product_detail.html" class="item-image">
<img src="{{data.image.url}}" alt="" />
</a>
<div class="item-info">
<h4 class="item-title">
{{data.name}}
</h4>
<p class="item-desc">{{data.description}}</p>
<div class="item-price">{{data.price}}</div>
<div class="item-discount-price">{{data.price_off}}</div>
</div>
</div>
{% endif %}
{% endfor %}
</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(".hit").on("click", function(ev)
{
ev.preventDefault();
var id = $(this).attr("id");
console.log(id)
$.ajax({
type : "GET",
url : '${}',
data : {
id : id
},
complete: function(data){
{#console.log(data, response.name, response.image, response.description);#}
$('ididid').html(data.responseText)
}
})
})
</script>
</div>
This is my index.html I try but it didn't work
Take a look at https://htmx.org/.
Also there is a Django package for it: https://github.com/adamchainz/django-htmx.
I am trying to implement dynamic tabs in my project that gives multiple tabs based on the values stored in the database.
In my case, I have two values stored in database so it's displaying just two, If I will increase more, it will show accordingly.
Category.objects.filter(category='MEDICINES')
Out[14]: <QuerySet [<Category: FRUITS>, <Category: GRAINS>]>
Here is my models.py file,
from django.db import models
from django.contrib.auth.models import User
STATUS = ((0, "Draft"), (1, "Publish"))
class Category(models.Model):
category_names = (
('DISEASES','DISEASES'),
('MEDICINES','MEDICINES'),
('ENCYCLOPEDIA','ENCYCLOPEDIA'),
)
category = models.CharField(max_length=100, choices=category_names)
sub_category = models.CharField(max_length=100, unique=True)
def __str__(self):
return self.sub_category
class Medicine(models.Model):
title = models.CharField(max_length=200, unique=True)
display_name = models.CharField(max_length=17, unique=True)
slug = models.SlugField(max_length=200, unique=True)
author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='medicine_posts')
category = models.ForeignKey(Category, on_delete=models.CASCADE)
updated_on = models.DateTimeField(auto_now=True)
content = models.TextField()
created_on = models.DateTimeField(auto_now_add=True)
status = models.IntegerField(choices=STATUS, default=0)
class Meta:
ordering = ["-created_on"]
def __str__(self):
return self.title
def get_absolute_url(self):
from django.urls import reverse
return reverse("medicine_detail", kwargs={"slug": str(self.slug)})
Here it my views.py file,
from django.views import generic
from .models import Medicine, Category
from django.shortcuts import render, get_object_or_404
class MedicineList(generic.ListView):
queryset = {'medicine' : Medicine.objects.filter(status=1).order_by("-created_on"),
'category' : Category.objects.all()
}
#queryset = Medicine.objects.filter(status=1).order_by("-created_on")
print(queryset)
template_name = "medicine.html"
context_object_name = 'element'
#paginate_by = 10
Here is my medicine.html file,
<div class="container">
<div class="row">
<div class="col-md-8 mt-3 left">
<nav>
<div class="nav nav-tabs nav-fill" id="nav-tab" role="tablist">
{% for item in element.category %}
<a class="nav-item nav-link active" id="{{ item.id }}" data-toggle="tab" href="#{{ item }}" role="tab" aria-controls="nav-home" aria-selected="true">{{ item }}</a>
{% endfor %}
</div>
</nav>
{% for item in element.category %}
<div class="tab-content py-3 px-3 px-sm-0" id="nav-tabContent">
<div class="tab-pane fade show active" id="{{ item }}" role="tabpanel" aria-labelledby="{{ item.id}}">
<table class="col-md-8 mt-3 left">
{% for post in element.medicine %}
{% cycle 'row' '' as row silent %}
{% if row %}<tr>{% endif %}
<td style="padding: 10px;">
<div class="card mb-4">
<div class="card-body">
<h6 class="card-title text-center"> {{ post.display_name }}</h6>
</div>
</div>
</td>
{% if not row %}</tr>{% endif %}
{% endfor %}
</table>
</div>
</div>
{% endfor %}
</div>
{% block sidebar %}
{% include 'sidebar.html' %}
{% endblock sidebar %}
</div>
</div>
Please help me out with this code, it;s not working.
Your queryset should not be a dictionary, Django expects a queryset instance here.
Try:
class MedicineList(generic.ListView):
queryset = Category.objects.all()
# or: model = Category
template_name = "medicine.html"
context_object_name = 'element'
I have trouble with adding comments to my django web-application. I want to add comments to allow users comment posts, like in normal web blog. I've tried a few ways, but nothing worked correctly for me.
After a few weeks searching and trying different ways to solve this question, I've stacked on this question. I have some progress, but it's now what I want completely.
Now I can only add "comments" from admin panel
and it look like this (from admin panel)
and like this (from user interface)
And I have this issue with padding comments( I don't really understand why it's occurs ¯_(ツ)_/¯ )
Anyway, here is my code, hope someone know how to solve this problem:
models.py
class Comment(models.Model):
post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments')
author = models.ForeignKey(User, on_delete=models.CASCADE)
text = models.TextField()
created_date = models.DateField(auto_now_add=True)
def __str__(self):
return self.text
...
class Post(models.Model):
title = models.CharField(max_length=200)
content = models.TextField()
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
categories = models.ManyToManyField('Category', related_name='posts')
image = models.ImageField(upload_to='images/', default="images/None/no-img.jpg")
slug= models.SlugField(max_length=500, unique=True, null=True, blank=True)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('post-detail', kwargs={'slug': self.slug})
post_detail.html
<article class="media content-section">
{% for comment in post.comments.all %}
<ul>
{{ comment.text }}
{% for reply in comment.replies.all %}
<li>
{{ reply.text }}
</li>
{% endfor %}
<ul>
{% endfor %}
</article>
I also read this article about creation blog for beginners, and they have working comment section as I want, but I tried to implement their code to my web-app, and nothing worked for me.
They have comment section like this (I need completely the same one):
But when I tried to follow their tutorial, I have only like this:
And here is the code for this unsuccessful solution( but I feel like it is working one, maybe I did something wrong)
post_detail.html
{% extends 'blog/base.html' %}
{% block content %}
<article class="media content-section">
<img class="rounded-circle article-img" src="{{ object.author.profile.image.url }}" alt="">
<div class="article-metadata">
<a class="mr-2 author_title" href="{% url 'user-posts' object.author.username %}">#{{ object.author }}</a>
<small class="text-muted">{{ object.date_posted|date:"N d, Y" }}</small>
<div>
<!-- category section -->
<small class="text-muted">
Categories:
{% for category in post.categories.all %}
<a href="{% url 'blog_category' category.name %}">
{{ category.name }}
</a>
{% endfor %}
</small>
</div>
{% if object.author == user %}
<div>
<a class='btn btn-secondary btn-sm mt-1 mb-1' href="{% url 'post-update' object.slug %}">Update</a>
<a class='btn btn-danger btn-sm mt-1 mb-1' href="{% url 'post-delete' object.slug %}">Delete</a>
</div>
{% endif %}
</div>
</article>
<article class="media content-section">
<div class="media-body">
<img class="img-fluid center" id="rcorners3" src="{{ object.image.url }}" alt="none">
<h2 class="article-title text-center">{{ object.title }}</h2>
<p class="article-content">{{ object.content }}</p>
</div>
</article>
<article class="media content-section">
<form action="/blog/{{ post.pk }}/" method="post">
{% csrf_token %}
<div class="form-group">
{{ form.author }}
</div>
<div class="form-group">
{{ form.body }}
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
<h3>Comments:</h3>
{% for comment in comments %}
<p>
On {{comment.created_on.date }}
<b>{{ comment.author }}</b> wrote:
</p>
<p>{{ comment.body }}</p>
<hr>
{% endfor %}
</article>
{% endblock content %}
views.py
...
def comment(request):
if request.method == 'POST':
form = CommentForm(request.POST)
if form.is_valid():
comment = Comment(
author=form.cleaned_data["author"],
body=form.cleaned_data["body"],
post=post
)
comment.save()
comments = Comment.objects.filter(post=post)
context = {
"post": post,
"comments": comments,
"form": form,
}
models.py
...
class Comment(models.Model):
post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments')
author = models.ForeignKey(User, on_delete=models.CASCADE)
text = models.TextField()
created_date = models.DateField(auto_now_add=True)
def __str__(self):
return self.text
forms.py
from django import forms
class CommentForm(forms.Form):
author = forms.CharField(
max_length=60,
widget=forms.TextInput(attrs={
"class": "form-control",
"placeholder": "Your Name"
})
)
body = forms.CharField(widget=forms.Textarea(
attrs={
"class": "form-control",
"placeholder": "Leave a comment!"
})
)
You are creating unnecessary lists. Try this one
<article class="media content-section">
<ul>
{% for comment in post.comments.all %}
<li>{{ comment.text }}</li>
{% if comment.replies.all %}
<ul>
{% for reply in comment.replies.all %}
<li>{{ reply.text }}</li>
{% endfor %}
</ul>
{% endif %}
{% endfor %}
<ul>
</article>