uploading image in Django inside a for loop - django

I wanted show the uploaded image from admin url in my index.html template. so i needed to put a for loop and I got a probelm in image src.
setting.py :
STATIC_URL = 'static/'
STATICFILES_DIRS = [
BASE_DIR / "static"
]
models.py :
class Home(models.Model):
image = models.ImageField(upload_to = "static")
titr = models.CharField(max_length=200)
description = models.TextField()
created = models.DateField(auto_now_add = True)
updated = models.DateField(auto_now = True)
class Meta:
ordering = ['created']
def __str__(self):
return str(self.titr)
views.py :
from django.shortcuts import render
from .models import Home
# Create your views here.
def index(request):
home = Home.objects.all()
context = {"homes" : home}
return render(request, 'home/index.html', context)
index.html(doesn't work) :
{% extends 'main.html' %}
{% block content %}
{% load static %}
{% for home in homes %}
<br>
<h1>{{home.titr}}</h1>
<img src="{% static '{{home.image.url}}' %}" style="width:50%" alt="My image">
<p>{{home.description}}</p>
<br><hr>
{% endfor %}
{% endblock content %}
index.html(work but it's not what i want):
{% extends 'main.html' %}
{% block content %}
{% load static %}
{% for home in homes %}
<br>
<h1>{{home.titr}}</h1>
<img src="{% static '{{home.image.url}}' %}" style="width:50%" alt="My image">
<p>{{home.description}}</p>
<br><hr>
{% endfor %}
{% endblock content %}

Related

How to load static file of a model in a html templates [duplicate]

This question already has answers here:
How to get an ImageField URL within a template?
(4 answers)
Closed 2 months ago.
I have a static file structure like this -----> static/images/article_images/images.png
here's my settings.py
STATIC_URL = 'static/'
STATICFILES_DIRS = [
BASE_DIR / "static",
# '/css/',
# 'images/article_image/',
]
here's what I tried:
{% extends "base.html" %}
{% block content %}
{% load static %} ---> i have this in my base.html
<div class="article-block" method="GET">
{% for article in articles %}
<!-- <img src="{{ article.image }}" alt="Article image"> -->
<img src="{% static '{{article.image}}' %}" alt="Article image">
<h2>{{ article.title }}</h2>
<p>{{ article.content }}</p>
{% endfor %}
</div>
{% endblock %}
here's my model.
from django.db import models
from django.conf import settings
def article_image_path(instance, filename):
return f"static/images/article_image/{filename}"
class Article(models.Model):
title = models.CharField(max_length=250)
content = models.CharField(max_length=1000)
image = models.ImageField(default='', upload_to=article_image_path)
def __str__(self):
return self.title
Static files are not bound by model. In your templates you should be using:
{% extends "base.html" %}
{% load static %} ---> include this line after extends in every template that require static files.
{% block content %}
<div class="article-block" method="GET">
{% for article in articles %}
<img src="{{ article.image }}" alt="Article image"/> <-- Use this if image is stored inside article model
<img src="{% static 'images/image_name.png' %}" alt="Article image"/> <--use this if your image is stored statically
<h2>{{ article.title }}</h2>
<p>{{ article.content }}</p>
{% endfor %}
</div>
{% endblock %}
Just remove article_image_path function from models.
And then, add path name in model field image directly.
For ex:
image = models.ImageField(default='', upload_to='images/') #path added here. uploaded images will store in this images folder. images folder will be created inside media folder automatically in your project root.
And in settings.py file just add media settings:
MEDIA_URL='/media/'
MEDIA_ROOT=os.path.join(BASE_DIR,'media')
In your main urls.py file, just add this:
+static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
EX:
urlpatterns = [
]+static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) #Added here
Note: don't forget to migrate the model after making changes in image field.

can't upload image from database in django server

in my project i am trying to save image in database and next i want to get that image from database
in my dashborad everything working well, imgs where saved in db but when i am trying to get url from db and asign it to img src="" chrome says that 404 (Not Found)
this is my model
class Id(models.Model):
first_name = models.CharField(max_length=100, null=True)
image = models.ImageField(default='defaut.jpg', upload_to='document_pics')
def __str__(self):
return self.first_nam
img savinig in documents_pics folder then i am trying to in views.py get data from db and send it to home.html
def home(request):
context = {
'posts': Id.objects.all(),
'title': 'Home'
}
return render(request, 'blog/home.html', context)
home.html
{% extends 'blog/base.html' %}
{% block content %}
{% for post in posts %}
<article class="media content-section">
<img src="{{ post.image }} " width="200" height="200"
</article>
{% endfor %}
{% endblock content %}
and than i am getting 404 error
Try these path on your image jinja code in your html template
{% extends 'blog/base.html' %}
{% block content %}
{% for post in posts %}
<article class="media content-section">
<img src="{{ post.image.url }} " width="200" height="200"
</article>
{% endfor %}
{% endblock content %

Reverse for 'allproduct' not found. 'allproduct' is not a valid view function or pattern name

urls.py
from django.urls import path
from . import views
app_name='shop'
urlpatterns = [
path('',views.allproduct,name='allproductcat'),
path('<slug:c_slug>/',views.allproduct,name='product_by_catagory')
]
views.py
from django.shortcuts import render, get_object_or_404
from . models import catagory,product
# Create your views here.
def allproduct(request,c_slug=None):
c_page=None
products=None
if c_slug!=None:
c_page=get_object_or_404(catagory,slug=c_slug)
products=product.objects.all().filter(catagory=c_page,available=True)
else:
products=product.objects.all().filter(available=True)
return render(request,'catagory.html',{'catagory':c_page,'products':products})
model.py
from django.db import models
# Create your models here.
from django.urls import reverse
class catagory(models.Model):
name=models.CharField(max_length=250,unique=True)
slug=models.SlugField(max_length=250,unique=True)
description=models.TextField(blank=True)
image=models.ImageField(upload_to='catagory',blank=True)
class Meta:
ordering=('name',)
verbose_name='catagory'
verbose_name_plural='catagories'
def __str__(self):
return '{}'.format(self.name)
def get_url(self):
return reverse('shop:product_by_catagory',args=(self.slug,))
class product(models.Model):
name = models.CharField(max_length=250, unique=True)
slug = models.SlugField(max_length=250, unique=True)
description = models.TextField(blank=True)
image = models.ImageField(upload_to='product', blank=True)
price=models.DecimalField(max_digits=10,decimal_places=2)
stock=models.IntegerField()
available=models.BooleanField()
created=models.DateTimeField(auto_now_add=True)
updated=models.DateTimeField(auto_now=True)
catagory=models.ForeignKey(catagory,on_delete=models.CASCADE)
class Meta:
ordering = ('name',)
verbose_name = 'product'
verbose_name_plural = 'products'
def __str__(self):
return '{}'.format(self.name)
catagory. html
{% extends 'base.html' %}
{% load static %}
{% block metadiscription %}
{% if catagory %}
{{catagory.discription}}
{% else %}
welcome
{% endif %}
{% endblock %}
{% block title %}
{% if catagory %}
{{catagory.name}}--ABC store
{% else %}
see our new collection
{% endif %}
{% endblock %}
{% block content %}
{% if catagory %}
<div>
<div>
OUR PRODUCT COLLECTION
</div>
</div>
{% endif %}
<div>
{% if catagory %}
<img src="{{catagory.img.url}}" alt="{{catagory.name}}">
</div>
<br>
<div>
<h1>
{{catagory.name}}
</h1>
<p>
{{catagory.discription}}
</p>
</div>
{% else %}
<div>
<img src="{% static 'img/banner.png' %}">
</div>
<br>
<div>
<h1>OUR PRODUCT COLLECTION</h1>
<p>INDIA IS MY COUNTRY I LOVE MY COUNTRY</p>
</div>
{% endif %}
<div>
<div>
{% for product in products %}
<div>
<div>
<div>
<h4>{{product.name}}</h4>
<p>{{product.price}}</p>
</div>
</div>
</div>
{% endfor %}
</div>
</div>
{% endblock %}
context_processors.py
from . models import catagory
def menu_link(request):
link=catagory.objects.all()
return dict(links=link)
i can't load the catagory page using the slug address,that is dress, when i enter that it is showing there is no revrse for allproducts, and when i open the website there is no image in image position.as i have uploaded the image file in the admin pannel
The name=… of your path is allproductcat, not allproduct, you thus should implement a link with:
OUR PRODUCT COLLECTION

Django - Static images render

I have a template that should render picture of each product.
But as result - URL for it has extra "static" in path
like that - 127.0.0.1:8000/static/static/photos/product1.png.
It should be just 127.0.0.1:8000/static/photos/product1.png
Is there any way to do it properly?
model.py saves it to "static/photos"
class Product(models.Model):
title = models.CharField(max_length=20)
photo = models.ImageField(upload_to='static/photos', default='http://placehold.it/700x400')
views.py
from django.shortcuts import render
# Create your views here.
from .models import Category, Product
def product_list(request):
queryset = Product.objects.all()
context = {"object_list": queryset}
return render(request, "product_list.html", context)
template.html is following
{% load static %}
{% for instance in object_list %}
<p><img src="{% static instance.photo %}" /></p>
{% endfor %}
Change this
{% for instance in object_list %}
<p><img src="{% static instance.photo %}" /></p>
{% endfor %}
To
{% for instance in object_list %}
<p><img src="{% static instance.photo.url %}" /></p>
{% endfor %}

Image won't load to template in Django, but is stored to Media file

I'm trying to get a posted image to display on a Listview Blog application.
Models.py
from django.db import models
class Post(models.Model):
image = models.ImageField(upload_to='Post_images',null=True)
title = models.CharField(max_length=100)
content = models.TextField()
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
success_url = "post-detail"
template_name = 'post_form.html'
urls.py
from django.conf.urls.static import static
from django.conf import settings
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
home.html
{% extends "blog/blogbase.html" %}
{% block content %}
{% for post in posts %}
{% if Post.image %}
<img src="{{ post.image.url }}" class="img-responsive">
{% else %}
<span class="text-muted">No cover</span>
{% endif %}
{% endfor %}
I see "No cover printed" on all of the posts indicatign that Post.image is not registering.
settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, '/media')
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(BASE_DIR, '/static')
STATIC_URL = '/static/'
I think it has to do with the media root, because when I upload the image it saves to the media file. I think the html/urls/settings connection is messed up.
Your error is in these lines in the template:
{% for post in posts %}
{% if Post.image %}
<img src="{{ post.image.url }}" class="img-responsive">
{% else %}
<span class="text-muted">No cover</span>
{% endif %}
{% endfor %}
In your second line, you have capitalized post from your for loop. It should be post.image, not Post.image.
The complete fixed code:
{% extends "blog/blogbase.html" %}
{% block content %}
{% for post in posts %}
{% if post.image %}
<img src="{{ post.image.url }}" class="img-responsive">
{% else %}
<span class="text-muted">No cover</span>
{% endif %}
{% endfor %}