can't upload image from database in django server - django

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 %

Related

How to tell jinja about files in static sub-directories?

I have created a web app in which user uploads a image on my web app and that image is saved in myproject/static/uploads directory but I am unable to display that image.
my file upload code:
file = request.files['file']
filename = secure_filename(file.filename)
if filename != '':
file_ext = os.path.splitext(filename)[1]
if file_ext not in current_app.config['UPLOAD_EXTENSIONS']:
return 'Invalid Image', 400
file.save(os.path.join(current_app.config['UPLOAD_FOLDER'], filename))
post = Post(title=title,body=body,author_id=current_user.id,author=current_user,filename=filename)
db.session.add(post)
db.session.commit()
return redirect(url_for('blog.index'))
return render_template('blog/create.html')
my index view:
#bp.route('/')
def index():
posts = Post.query.all()
files = os.listdir(current_app.config['UPLOAD_FOLDER'])
return render_template('blog/index.html', posts=posts, files=files)
index.html
{% block content %}
{% for post in posts %}
<article class="post">
<header>
<div>
<h1>{{ post.title }}</h1>
<div class="about">by {{ post.author.username }} on {{ post.created.strftime('%Y-%m-%d') }}</div>
</div>
</header>
<p class="body">{{ post.body }}</p>
</article>
{% for file in files %}
<img src="{{ url_for('static', filename='uploads/post.filename') }}" style="width: fit-content;">
{% endfor %}
{% if not loop.last %}
<hr>
{% endif %}
{% endfor %}
{% endblock %}
You have to use string concatenation to create the dynamic filename:
<img src="{{ url_for('static', filename='uploads/' ~ post.filename) }}" style="width: fit-content;">
The preferred operator is the tilde (~), but you can also use the plus operator if you wish.
You can simply do this in your main file:
app = Flask(__name__,
static_url_path='',
static_folder='templates/static',
template_folder='templates')
And then call your files: (path for 'example.js' is 'app/templates/static/js')
<img width="130" src="/js/example.js">

Django Default Image is showing

why i can't see default image here below are my model and profile.html file:
Model:
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Profile(models.Model):
user = models.OneToOneField(User,on_delete=models.CASCADE)
image = models.ImageField(upload_to='profile_pics',default='default.jpg')
def __str__(self):
return f'{self.user.username} Profile'
Profile.html:
{% extends 'blog/base.html' %}
{% load crispy_forms_tags %}
{% block content %}
<div class="content-section">
<div class="media">
<img class="rounded-circle account-img" src="{{ user.profile.image.url }}">
<div class="media-body">
<h2 class="account-heading">{{ user.username }}</h2>
<p class="text-secondary">{{user.email}}</p>
</div>
</div>
<!-- FORM HERE -->
</div>
{% endblock content %}
Thank you in advance...
in templates you can check the image exists or not, if not can show a default image from static file as follows
{% if user.profile.image %}
<img src="{{ user.profile.image.url }}">
{% else %}
<img src="{% static 'img/default.png' %}">
{% endif %}

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 %}

Django model filtering(query)

I'm struggling with a model filtering, what I doing wrong? Here is my code:
models.py
class Images(models.Model):
TAK_NIE = (
('y', 'Tak'),
('n', 'Nie')
)
nazwa_polska = models.ForeignKey(Roslina, related_name='images', on_delete=models.CASCADE)
image = models.ImageField(max_length=255, upload_to=generate_filename)
zdjecie_glowne = models.CharField(max_length=1,choices=TAK_NIE,default='n')
def czyGlowne(self):
return self.filter(zdjecie_glowne='y')
def __str__(self):
return self.nazwa_polska.nazwa_polska
html not working:
{% for zdjecie in ros.images.czyGlowne %}
{{ zdjecie.image }}
<img src="{% static '' %}{{ zdjecie.image|cut:"static/"}}" alt="brak
zdjecia" class="img-thumbnail zdjecia">
{% endfor %}
on the same page working html code:
{% for zdjecie in ros.images.all %}
<div class="col-lg-4">
<img src="{% static '' %}{{ zdjecie.image|cut:"static/"}}" alt="brak
zdjecia" class="img-thumbnail zdjecia">
</div>
{% endfor %}
Your view should be filtering or creating the filtered queryset.
You can also filter like this:
{% for zdjecie in ros.images.all %}
(% if zdjecie.zdjecie_glowne == 'y' %}
{{ zdjecie.image }}
<img src="{% static '' %}{{ zdjecie.image|cut:"static/"}}" alt="brak
zdjecia" class="img-thumbnail zdjecia">
{% endif %}
{% endfor %}

Django: How to show all images in images model

I am trying to show all images associated with the currently selected user
This is built off of this solved question: django upload to image model with foreign key to user
Model.py
class Images(models.Model):
image = models.ImageField(upload_to='profile_image', null=True, default='profile_image/none/no-img.png')
user = models.ForeignKey(User, on_delete=models.CASCADE)
Views.py
#login_required
def index_account(request):
args = {'user': request.user }
return render(request, 've/cp/index_account.html', args)
Template > index_account.html
<p>Edit your images</p>
# test to see if it worked w/o if
{{ user.images.image}}
# ideal solution
{% if user.images.images %}
{% for img in user.images %}
<img src="{{ user.images.image.url }}"><br>
{% endfor %}
{% else %}
<p>No images</p>
{% endif %}
<br>
<hr>
The code you have provided is not going to work for what you want. So here is an example of something that probably will:
Example
views.py
from app_name.models import Images
#login_required
def index_account(request):
images = Images.objects.filter(user=request.user)
return render(request, 've/cp/index_account.html', {"images": images})
index_account.html
<p>Edit your images</p>
# ideal solution
{% if images %}
{% for img in images %}
<img src="{{ img.url }}"><br>
{% endfor %}
{% else %}
<p>No images</p>
{% endif %}
<br>
<hr>
Hope this helps!