I have this app in which I need to display an image on the html template which is not happening.
models.py
class cateledetails(models.Model):
cdid=models.IntegerField(unique=True,default=0)
cid=models.ForeignKey(category,to_field='cid',on_delete=models.CASCADE)
elename=models.CharField(max_length=20)
imgsrc=models.ImageField(upload_to='elements/',blank=True)
def __unicode__(self):
return u"{} {}".format(self.cdid,self.elename)
class Meta:
db_table="cateledetails"
views.py
def mainpage(request):
pic_details=get_object_or_404(cateledetails,pk=1)
template=loader.get_template('student/mainpage.html')
context={'pic_details': pic_details,}
return HttpResponse(template.render(context,request))
urls.py
urlpatterns= [
url(r'^mainpage/$',views.mainpage ,name='mainpage'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
mainpage.html
{% block body %}
<form action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
<h4>What sound does it make?</h4>
{% for image in pic_details.imgsrc_set.all %}
<img src="{{ image.imgsrc.url }}" alt="image">
{% endfor %}
</form>
{% endblock %}
what do I do?
pic_details is a cateledetails object.
This class has a single ImageField called imgsrc. Since imgsrc isn't a ForeignKey you can't use the ForeignKey <field>_set syntax with it. Instead, simply refer to the field directly:
{% block body %}
<form action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
<h4>What sound does it make?</h4>
<img src="{{ pic_details.imgsrc.url }}" alt="image">
</form>
{% endblock %}
Related
i am trying to display image from db with views and in the inspact broswer i see it find my image but still return me 404 error. my models.py:
class HomePhoto(models.Model):
title = models.CharField(max_length=100)
img = models.ImageField(upload_to='home_page_images/')
view.py:
def index(request):
data = HomePhoto.objects.all()
return render(request, 'home.html',{'data':data,})
html:
{% for d in data %}
<img src="{{d.img}}" alt="Third slide">
{% endfor %}
url.py:
urlpatterns = [
path('',views.index,name='index')
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
the html in the broswer inspact:
<img src="home_page_images/orangeshirt_1ZrO8ay.jpg" alt="Third slide"> <!--THIS IS THE RIGHT PATH AND THE RIGHT NAME OF THE IMAGE-->
You are forgetting about accessing the url member:
{% for d in data %}
<img src="{{d.img.url}}" alt="Third slide">
{% endfor %}
{% for d in data %}
<img src="{{d.img.url}}" alt="Third slide">
{% endfor %}
you need to add url: d.img.url
Try this:
{% load static %}
<img src="{% static 'my_app/example.jpg' %}" alt="My image">
I just want to display profile picture.Img upload successfully but not showing the img.But if i try in admin panel then show me img. Here is my index.html code
{% extends 'Login_app/base.html' %}
{% block body_block %}
{% if user.is_authenticated %}
<p>Hi {{ user_basic_info.username }},</p>
<p>Your Email {{ user_basic_info.email }}</p>
<p> Facebook Profile </p>
<img src="/media/{{ user_more_info.profile_pic }}" width="200px">
{% else %}
<div class="alert alert-primary"></div>You are not logged in!!</div>
{% endif %}
{% endblock %}
Here is my setting.py media setting
import os
MEDIA_ROOT = os.path.join(BASE_DIR, 'media') # This is a tuple
MEDIA_URL = '/media/'
Here the ss of website
You have to add .url after the profile picture.
Try This:
<img src="/media/{{ user_more_info.profile_pic.url }}" width="200px">
OR
In Models.py define a get_absolute_url() method to join the media directory:
def get_absolute_image(self):
return os.path.join('/media', self.image.name)
And in templates do this:
{% for post in posts %}
<img src="{{ post.get_absolute_image }}" width="200px">
{% endfor %}
p.s.- here post is model name
django setting
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),
)
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
django views
def single_article(request, page, slug):
article = get_object_or_404(Article, slug=slug)
return render(request, "article/single_article.html", locals())
django template
<`enter code here`img class="d-block w-100 img-responsive" style="height: 100%" src="{{ article.picture.url }}" alt="{{ article.title }}"
> Blockquote
you don't have to pass /media/ or use .url to fetch it from db
{% extends 'Login_app/base.html' %}
{% block body_block %}
{% if user.is_authenticated %}
<p>Hi {{ user_basic_info.username }},</p>
<p>Your Email {{ user_basic_info.email }}</p>
<p> Facebook Profile </p>
<img src="{{ user_more_info.profile_pic.url }}" width="200px">
{% else %}
<div class="alert alert-primary"></div>You are not logged in!!</div>
{% endif %}
{% endblock %}
this will work if still image is not loadin add you views
Try to add this code to the project's urls.py:
urlpatterns = [
...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
I'm new to Django. In my app, I'm working on an image uploading and displaying function. I have tried setting up the MEDIA_URL and Media_ROOT. I also add the static path to the urls.py file and make sure that in HTML template object.image.url is used. However, the image is not displayed. Any help is greatly appreciated!
Edit 1 (Add project structure):
This is a screenshot of my project structure:
link to my project structure screenshot
Edit 2 (Add screenshots of browser):
link to browser screenshot
django admin page
the image in browser
Edit 3 (Add screenshot of browser inspect window)
image of browser inspect window
My code is as followed:
urls.py
from django.contrib import admin
from django.urls import include, path
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
path("admin/", admin.site.urls),
path("", include("auctions.urls"))
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
views.py
class ListingForm(ModelForm):
def __init__(self, *args, **kwargs):
super(ListingForm, self).__init__(*args, **kwargs)
for field in iter(self.fields):
self.fields[field].widget.attrs.update({
'class': 'form-control'
})
class Meta:
model = Listing
fields = ['title', 'description', 'current_price', 'image', 'category']
def index(request):
return render(request, "auctions/index.html", {
"active_listings" : Listing.objects.all()
})
def createListing(request):
if request.method == "POST":
listing_data = ListingForm(request.POST, request.FILES)
if listing_data.is_valid():
title = listing_data['title']
description = listing_data.cleaned_data['description']
current_price = listing_data.cleaned_data['current_price']
if listing_data.cleaned_data['image']:
image = listing_data.cleaned_data['image']
else:
image = None
category = listing_data.cleaned_data['category']
listing = Listing(title=title, description=description, current_price=current_price, image=image, category=category)
listing.save()
return HttpResponseRedirect(reverse("index"))
return render(request, "auctions/createListing.html", {
"listingForm" : ListingForm()
})
models.py
class Listing(models.Model):
class Category(models.TextChoices):
FASHION = 'FA', _('Fashion')
TOYS = 'TO', _('Toys')
ELECTRONICS = 'EL', _('Electronics')
HOME = 'HO', _('Home')
OTHERS = 'OT', _('Others')
title = models.CharField(max_length=64)
description = models.TextField()
current_price = models.IntegerField()
image = models.ImageField(upload_to='listingImages', blank=True)
category = models.CharField(max_length=64, blank=True, choices=Category.choices)
settings.py
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
index.html
{% extends "auctions/layout.html" %}
{% block body %}
<h2>Active Listings</h2>
<ul>
{% for listing in active_listings %}
<li>Title: {{ listing.title }}</li>
<li>Description: {{ listing.description }}</li>
<li>Current Price: {{ listing.current_price }}</li>
{% if listing.image %}
<li>
<img scr="{{ MEDIA_URL }}{{ listing.image.url }}" alt="{{ listing.image.url }}">
</li>
{% endif %}
{% endfor %}
</ul>
{% endblock %}
createListing.html
{% extends "auctions/layout.html" %}
{% block body %}
<h1>Create A New Listing</h1>
<form action="{% url 'createListing' %}" method="POST" enctype="multipart/form-data">
{% csrf_token %}
{% for field in listingForm %}
<div class="form-group">
{{ field.label }} {{ field }}
</div>
{% endfor %}
<input type="submit" value="Done">
</form>
{% endblock %}
Replace src attribute in your img tag from this:
scr="{{ MEDIA_URL }}{{ listing.image.url }}"
to this:
scr="{{ listing.image.url }}"
Also you can try to add a line like this to check if image exists at all:
{% if listing.image %}
<li>
<img scr="{{ MEDIA_URL }}{{ listing.image.url }}" alt="{{ listing.image.url }}">
</li>
{% else %}
<p> Image doesnt exist. </p>
{% endif %}
UPDATE
Try making your main urls.py like this:
urlpatterns = [
path("admin/", admin.site.urls),
path("", include("auctions.urls"))
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
Instead of what you have right now.
I have setup django-summernote on my project and everything is great, it works very good on admin , but i want to use it on my templates.
Note :
in django-summernote documentation they only explain how to use it if you have forms.py file but I dont
my main urls.py :
urlpatterns = [
path('games/', include('core.urls', namespace='core')),
path('summernote/', include('django_summernote.urls')),
]
my app(name=core) urls.py :
from django.urls import path
from . import views
app_name = 'core'
urlpatterns = [
path('new/', views.GameCreate.as_view(), name='game_new'),
path('<int:pk>/edit/', views.GameUpdate.as_view(), name='game_edit'),
]
my views.py :
class GameCreate(LoginRequiredMixin, CreateView):
model = Game
template_name = 'core/game_new.html'
fields = '__all__'
redirect_field_name = 'home'
class GameUpdate(LoginRequiredMixin, UpdateView):
model = Game
template_name = 'core/game_edit.html'
fields = '__all__'
my template file "game_new.html" :
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% block title %} Add New Game {% endblock %}
{% block main %}
<section class="main-section">
<div class="container">
<h1>New Game</h1>
<form action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form|crispy }}
<input type='submit' value="Save" />
</form>
</div>
</section>
{% endblock %}
my template file "game_edit.html":
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% block title %} Game Info {% endblock %}
{% block main %}
<section class="main-section"></section>
<div class="container">
<h1>Edit Game Info</h1>
<form action="" method="post">
{% csrf_token %}
{{ form|crispy }}
<input type="submit" value="Update" />
</form>
</div>
</section>
{% endblock %}
my Models.py :
from django.db import models
from django.urls import reverse
# Create your models here.
class Game(models.Model):
name = models.CharField(max_length=140)
developer = models.CharField(max_length=140)
game_trailer = models.CharField(max_length=300, default="No Trailer")
game_story = models.TextField(default='No Story')
Firstly in your template dont forgate to add this:
{{ form.media }} <<<------ To load all js and css attached
In the document your models you must herit summernote widget. Example:
from django_summernote.widgets import SummernoteWidget, SummernoteInplaceWidget
class FormFromSomeModel(forms.ModelForm):
class Meta:
model = SomeModel
widgets = {
'foo': SummernoteWidget(),
'bar': SummernoteInplaceWidget(),
}
I have a model with a ImageField and created an simple Upload Form via CreateForm. I have a simple ListView to show the images (logos).
Upload works fine, Iterating the logos works. Property logo.url is missing but instead it is logo.media. Unfortunately media does not contain the whole path, MEDIA_ROOT is missing. What am I doing wrong here?
models.py:
class Logo(models.Model):
media = models.ImageField(upload_to='uploads')
views.py:
class LogoManager(CreateView):
model = Logo
template_name = 'polls/upload.html'
success_url = '/logos/'
class LogoIndex(ListView):
model = Logo
template_name = 'polls/logos.html'
upload.html:
{% block title %} Upload Form {% endblock %}
{% block content %}
<form id="my_form" action="" method="post" enctype="multipart/form-data">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Save Changes" />
</form>
<br />
Back
{% endblock %}
logos.html:
{% block content %}
{% if object_list %}
<ul>
{% for image in object_list %}
<li><img src="{{ image.media }}" width="320" height="200"/></li>
{% endfor %}
</ul>
{% else %}
<p>No Logos are available.</p>
{% endif %}
<br />
{% endblock %}
Output is:
<li><img src="uploads/IMG_5106.JPG" width="320" height="200"/></li>
You'll want to use {{ image.media.url }}, I think.
OK, it was my wrong. I was editing the url in the apps url file. When adding this stanza in root urls.py it works fine:
if settings.DEBUG:
urlpatterns += patterns('django.views.static',
(r'%s(?P<path>.*)' % settings.MEDIA_URL, 'serve', {'document_root': settings.MEDIA_ROOT}),
)
using settings.py:
MEDIA_URL = '/media/'