Just wanting to make a simple multiple page website and I cant seem to get the background image to show on local host, Django just keeps saying Image not found. Can anyone help with this?? I want to drop vue in and do some fun stuff, but If I can't even get the images to show its going to be no fun at all.
The HTML File.
<body>
<section id="hero" class="d-flex align-items-center">
<div id="bg">
<div class="bg">
<img
src="{% static "media/ocean.jpg" %}"
class="bg1"
alt=""
/>
My View File
from django.shortcuts import render
# Create your views here.
def homepage(request):
return render(request, '/Users/mossboss/Dev/SimpleWS/apps/core/templates/core/base.html')
My Settings
STATIC_URL = '/static/'
STATICFILES_DIRS = [
BASE_DIR / 'static'
]
MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR / 'media'
Related
A am working on a simple application, where trying to generate Dynamic URl and routing take place as per the ID in the url.
Dynamic value is getting populated in the URL, but it not performing action that needed.
prop_listings.html HTML Page:-
<div class="row text-secondary pb-2">
<div class="col-6">
<i class="fas fa-clock"></i> {{ listing.list_date | timesince }}
</div>
</div>
<hr>
More Info
</div>
</div>
</div>
URL.py in App Listings:-
from django.urls import path
from . import views
urlpatterns = [
path('',views.PropListings,name="prop_listings"),
path('<int:listing_id>', views.mlisting, name="morelisting"),
]
Views.py :-
def mlisting(request, listing_id):
# listingDetl = get_object_or_404(Listing, pk=listing_id)
listingDetl = Listing.objects.get(pk=listing_id)
print(listingDetl.username, listingDetl.address,listingDetl.city)
context = {
'listingDetails': listingDetl
}
return render(request,'listings/detail_listing.html', context)
URL.py in MainProject:-
urlpatterns = [
path('', include('static_pages.urls')),
path('user_account/', include('user_account.urls')),
path('listings/', include('listings.urls')),
path('feedback/', include('feedback.urls')),
path('admin/', admin.site.urls),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Am trying to redirect the page from prop_listings.html to detail_listing.html, based on the below tag URL generated on listing.id
More Info
It's not working as expected on-click of above tag.
But when i did inspect on the same, URL is getting generated properly and when i click on the url, it will work as expected.
Inspect on the html page, URL populated
I looked into similar issue threads and tried to make changes, but not able to fix it.
Not getting what the issue and how to correct it.
I tried to display my edited image with PIL package, when I tried to make it to display on the html <img src=''></img> it doesn't appear anything, but I see the file name on inspect elements was <img src="<_io.BytesIO object at 0x000001EDA8F76E00>">. How do I make the edited image display properly?
app.py
#app.route("/api/games/shipper/image/", methods=["GET"])
def games_shipper():
... # My stuff up here
image_io = BytesIO()
img.save(image_io, "PNG")
image_io.seek(0)
return render_template('image.html', image_data=image_io)
image.html
... // My stuff up here
<body>
<center>
<image src="{{ image_data }}"></image>
</center>
</body>
You can read the data from the buffer with the getvalue() function and then convert it. The base64 encoded data can then be passed to the src parameter as a data url.
from base64 import b64encode
#app.route("/api/games/shipper/image/", methods=["GET"])
def games_shipper():
... # My stuff up here
image_io = BytesIO()
img.save(image_io, 'PNG')
dataurl = 'data:image/png;base64,' + b64encode(image_io.getvalue()).decode('ascii')
return render_template('image.html', image_data=dataurl)
If you pass the image as a dataurl, there is no way to shrink the string. However, there is the possibility of serving the file as pure image data. You can use send_file in another endpoint for this. You serve the page (template) in one endpoint and the image file in a second.
from flask import send_file
#app.route('/')
def index():
return render_template('index.html')
#app.route('/image')
def game_shipper():
# ...
image_io = io.BytesIO()
img.save(image_io, format='PNG')
image_io.seek(0)
return send_file(
image_io,
as_attachment=False,
mimetype='image/png'
)
<body>
<center>
<img src="{{ url_for('game_shipper') }}" />
</center>
</body>
You'll need to encode your image in Base64 to display it in the img tag directly, see e.g. How to display Base64 images in HTML
The traditional way to display images in Flask templates is to save the image in Flask's static folder and link to it in your template like so
<body>
<center>
<image src="/static/{{image_name}}.png"></image>
</center>
</body>
I'm new to Django and I'm facing a problem of loading a static file (image). I got
127.0.0.1/:1707 GET http://127.0.0.1:8000/static/css/static/images/background/1.jpg 404 (Not Found)
I'm pretty sure that the problem is on the path but I can't understand where this /static/css/ comes from. Could you please help me?
My settings.py file:
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'evillio/static')
]
My index.html file:
<!-- First Page with Picture and Search Starts -->
<section class="home-one home1-overlay **home1_bgi1**">
<div class="container">
<div class="row posr">
<div class="col-lg-12">
<div class="home_content">
<div class="home-text text-center">
<h2 class="fz55">Find Your Dream Home</h2>
<p class="fz18 color-white">From as low as $10 per day with limited time offer discounts.</p>
</div>
My CSS file:
home1_bgi1{
background-image: url('static/images/background/1.jpg');
-webkit-background-size: cover;
background-size: cover;
background-position: center center;
height: 960px;
When inspecting the page
Did you include {% load static %} at the top ??
For the latest version of Django, it doesn't use that in Setting.py:
`STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'evillio/static')
]`
Instead of this for Django 3.1 change code as bellow:
`STATICFILES_DIRS = [
BASE_DIR / "static",
'/var/www/static/',
]`
Read the documentation of Django 3.1, it has some code updated in the previous version of Django.
https://docs.djangoproject.com/en/3.1/howto/static-files/
I am building my own blog site.
I managed to have the users upload their own profile pic and have it displayed beside their post but now i want to have that same image be displayed in the navbar as a profile image but when i do it the same way i did it with the posts it doesnt work and looks like this.
For the posts i made a profile image model and accessed the variable from within the html file but the same method does not work for displaying it in the nav bar.
I am using python and django for backend.
This is my model code for the profile image:
from django.db import models
from django.contrib.auth.models import User
from PIL import Image
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
image = models.ImageField(default="default.jpg", upload_to="profile_pics")
def __str__(self):
return f"{self.user.username} Profile"
def save(self, *args, **kwargs):
super().save(*args, **kwargs)
img = Image.open(self.image.path)
if img.height > 300 or img.width > 300:
output_size = (300, 300)
img.thumbnail(output_size)
img.save(self.image.path)
This is how i reference it in my html file for displaying next to posts:
<img class="rounded-circle article-img" src="{{ post.author.profile.image.url }}" id="img">
When i use any other image(either from a url or a local file) it works perfectly but when I use that variable to call the image it doesn't work
It might be worth mentioning that the navbar and post sections are in different html files. it looks like the nav bar's html file does not have access to that variable?
What am I doing wrong?
Try this:
<img class="rounded-circle article-img" src="{{ request.user.profile.image.url }}" id="img">
Hi i'm currently new to Django and i'm trying to populate a product page.
I'm having problem with the img to show the image(which uses an image url online instead of a file) for example an img src="media3.scdn.vn/img2/2018/6_2/ZIBLXA_simg_b5529c_250x250_maxb.jpg"
The url already in my database with the text media3.scdn.vn/img2/2018/6_2/ZIBLXA_simg_b5529c_250x250_maxb.jpg
But when i tried to render it in template the image doesn't show
I tried to used the but it still not work
Any help would be appreciate!
My template
{% for discount in discounts|slice:":8" %}
<div class="col-md-3 product-men women_two">
<div class="product-googles-info googles">
<div class="men-pro-item">
<div class="men-thumb-item">
<img src="{{STATIC_URL}}{{discount.product_image}}" alt="" />
<div class="men-cart-pro">
<div class="inner-men-cart-pro">
Quick View
</div>
</div>
<span class="product-new-top">New</span>
</div>
<div class="item-info-product">
<div class="info-product-price">
<div class="grid_meta">
<div class="product_price">
<h4>
{{discount.product_name}}
</h4>
<div class="grid-price mt-2">
<span class="money">{{discount.product_old_price}}</span>
</div>
</div>
<div>
<h3>{{discount.product_sit}}</h3>
</div>
<div><h2 style="color: red;">Only {{discount.product_price}}!</h2></div>
</div>
</div>
<div class="clearfix"></div>
</div>
</div>
</div>
</div>
{% endfor %}
EDIT
Seems like the image src trying to get is "http://127.0.0.1:8000/media3.scdn.vn/img2/2018/6_2/ZIBLXA_simg_b5529c_250x250_maxb.jpg" which i don't want "http://127.0.0.1:8000/" in the link. Is there a way to remove this when using {{discount.product_image}} tag ?
Main project urls.py:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('frontend.urls')),
]
frontend app urls.py:
from django.urls import path
from .import views
from django.conf import settings
from django.conf.urls.static import static
app_name = 'frontend'
urlpatterns = [
#index
path('',views.index, name='index')
]
Try using .url like this.
<img src="{{ discount.product_image.url }}" alt=""/>
Also add the MEDIA and STATIC url to your project url patterns.
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URL pattern goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) \
+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
EDIT:
From the discussion in chat, I understood that I had misunderstood your problem first. The images are external and not in your db, you are just storing the URL to the images. And you are using a TextField not ImageField. I assumed ImageField previously. So, all you have to do is to replace {{STATIC_URL}} from in front of the actual URL and put http:// there. The reason behind this is, as the src is missing http:// it's assumed the image to be in the same host domain. So it goes to http://127.0.0.1/your_url.
<img src="http://{{ discount.product_image }}" alt=""/>