I have tried so many things to fix this issue but still I can't get it to work.
I can't get my MEDIA images to render correctly in the template, although the url in the page source is the correct absolute path, still the images won't appear.
models.py
from django.db import models
from django.contrib.auth.models import User
from django.conf import settings
import os
class Contact(models.Model):
user = models.OneToOneField(User,null=True)
website = models.URLField(blank=True,null=True)
db = models.ImageField(upload_to=settings.MEDIA_ROOT)
def __unicode__(self) :
return unicode(self.user) or u''
views.py
from django.shortcuts import render
from .models import Contact
from django.contrib.auth.models import User
def user_page(request,user_name):
try :
user = User.objects.get(username=user_name)
except User.DoesNotExists :
return (request,'main.html')
return render(request,'main/user_page.html',{'user':user})
urls.py
from django.conf.urls import url
from django.conf.urls.static import static
from django.conf import settings
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
import views
urlpatterns = [
url(r'^(?P<user_name>\w+)/$',views.user_page , name = 'main_page'),
]
if settings.DEBUG :
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += staticfiles_urlpatterns()
main/user_page.html
{% load staticfiles %}
<h1>{{user.username}}</h1>
<img src="{{user.contact.db.url}}" alt="My image"/>
settings.py
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR,'static','static_root')
STATIC_DIR = (
os.path.join(PROJECT_DIR,'static'),
)
MEDIA_ROOT =os.path.join(BASE_DIR,'media')
MEDIA_URL = '/media/'
Thanks and sorry for the bad english
db = models.ImageField(upload_to=settings.MEDIA_ROOT)
Is wrong. Quote form documentation:
FileField.upload_to
A local filesystem path that will be
appended to your MEDIA_ROOT setting to determine the value of the url
attribute.
Thus:
db = models.ImageField(upload_to="foo")
Will upload to MEDIA_ROOT + "foo".
Try doing this instead:
models.py:
class Contact(models.Model):
user = models.OneToOneField(User,null=True)
website = models.URLField(blank=True,null=True)
db = models.ImageField(upload_to=some_folder_here)
def __unicode__(self) :
return unicode(self.user) or u''
def get_db_url(self):
return "{}{}".format(settings.MEDIA_URL, self.db)
views.py:
def user_page(request,user_name):
try :
user = User.objects.get(username=user_name)
photo = Contact.objects.filter(user=user)
except User.DoesNotExists :
return (request,'main.html')
context = {
'user': user',
'photo': photo
}
return render(request,'main/user_page.html', context)
html:
{% load staticfiles %}
<img src="{{ photo.get_db_url }}" alt="My image" />
Related
hi when i am saving images from my admin they are saved in project directory like this images/images/myimg.jpg.. but when i am trying to display them in my template like this
<img src="{{About.image.url}}" alt="profile photo">
the image do not displays.. when i inspect the page in chrome... it shows image source unknown..
<img src="(unknown)" alt="profile photo">
please see the files ..
settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS =[
os.path.join(BASE_DIR,'portfolio/static')
]
STATIC_ROOT = os.path.join(BASE_DIR,'media')
MEDIA_URL ='/media/'
MEDIA_ROOT = os.path.join(BASE_DIR,'images')
project urls.py
from django.contrib import admin
from django.urls import path,include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('home/', include("home.urls")),
path('blog/', include("blog.urls")),
] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT )
the model having image is inside a app named 'home'
models.py of home app
from django.db import models
import datetime
# Create your models here.
class About(models.Model):
image = models.ImageField(upload_to = 'images')
desc = models.TextField()
home/views.py
from django.shortcuts import render
from home.models import *
from django.views.generic import ListView
# Create your views here.
def index(request):
abt = About.objects.all()
return render(request,'home/index.html',{'abt': abt.first()})
def Experience(request):
Exp = Experience.objects.all()
return render(request,'home/Experience.html',{'Exp': Exp})
class MyView(ListView):
context_object_name = 'name'
template_name = 'home/index.html'
queryset = About.objects.all()
def get_context_data(self, **kwargs):
context = super(MyView, self).get_context_data(**kwargs)
context['Experience'] = Experience.objects.all()
context['Education'] = Education.objects.all()
context['Award'] = Award.objects.all()
context['Membership'] = Membership.objects.all()
context['About'] = self.queryset
return context
if about you're passing queryset so try looping them and accessing each image
{% for data in About %}
<img src="{{data.image.url}}" alt="profile photo">
{% endfor %}
A beginner building a personal blog. Got a simple model with an ImageField. No matter what I try the Django won't serve an image.
Judging by the console output in the Dev Tools it is looking for an image in the wrong folder. I don't know how to fix that. I tried setting up MEDIA_URL, MEDIA_ROOT and adding a urlpattern like it's being suggest here and here
I have uploaded the picture via admin panel, its location is media/images/stockmarket.jpg. But for some reason the server is looking for an image here /blog/images/stockmarket.jpg
Project name: 'wikb', 'blog' is an App:
project_file_system
models.py
from django.db import models
class Post(models.Model):
title = models.CharField('Post Title', max_length=200)
preview = models.CharField('Post Preview', max_length=400)
thumbnail = models.ImageField('Post Picture', upload_to='images/', blank=True)
view.py
from django.shortcuts import render
from django.http import HttpResponse
from .models import Post
def home(request):
all_posts = Post.objects.all()
hero_post = all_posts[0]
context = {'hero_post': hero_post, 'all_posts': all_posts}
return render(request, 'blog/home.html', context=context)
HTML
<div class="hero">
<a href="#" class="hero__link" style="background-image: url({{hero_post.thumbnail}})">
<article class="hero__article">
<h2 class="hero__heading">{{hero_post.title}}</h2>
<p class="hero__preview">{{hero_post.preview}}</p>
</article>
</a>
</div>
settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
MEDIA_URL = "/media/"
Global urls.py
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('blog/', include('blog.urls')),
path('admin/', admin.site.urls),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
It's my first Django project, please explain like I'm 5.
Update: I forgot to add .url when I referenced an object in templates.
In templates, you'll want to use .url to get the real URL of a FieldFile (the file contained by a FileField or ImageField):
<a href="#" class="hero__link" style="background-image: url({{ hero_post.thumbnail.url }})">
I want to make a app in which admin upload a image on admin panel and it display on the template. I'm know there are some question related to this but I tried all of them but still can't display image.
Django version: 2.1.4
python version: 3.6.7
In setting.py
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'image')
In model.py
from django.db import models
class ImageModel(models.Model):
caption = models.CharField(max_length=40)
image = models.ImageField(upload_to='uploadImage', blank=True)
def __str__(self):
return self.caption
In view.py
from django.shortcuts import render
from .models import ImageModel
def image_page(request):
images = ImageModel.objects.all()
return render(request, 'input/hello.html', {'image':images})
In urls.py
from django.contrib import admin
from django.urls import path, include
from image import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.image_page),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
In imageShow.html
<img src="{{ ImageModel.image.url }}" alt="image" />
doing this show me a broken image and some time the full url of the image(where is the image is saved) What I'm doing wrong. I try to print variable images in views.py and it print my caption("image") so it means that it sending caption in img tag not the image itself? should I make a new class of ImageUpload?
thanks in advance
You need to iterate through ImageModel queryset (which you are sending as context via variable image) and show the image in template, like this:
{% for im in image %}
<img src="{{ im.image.url }}" alt="image" />
{% endfor %}
There are lots of answer on how to upload media files, what are the correct configuration and how to serve it on our application.
But my project seems to work nothing.
The aim is simple: User uploads an image. Django displays it on.
models.py
class UploadImageModel(models.Model):
image = models.FileField()
title = models.CharField(max_length=100, null=True, blank=True)
urls.py
from django.conf.urls import url, include
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'', include("Image.urls")),
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
views.py
from django.shortcuts import render
from django.views import View
from .forms import UploadImageModelForm
from .models import UploadImageModel
# Create your views here.
class UploadImage(View):
def get(self, request, *args, **kwargs):
form = UploadImageModelForm()
context = {
"form":form,
}
return render(request, "index.html", context)
def post(self, request, *args, **kwargs):
form = UploadImageModelForm(request.POST or None, request.FILES or None)
if form.is_valid():
instance = form.save(commit=False)
instance.title = str(instance.image)
instance.save()
context = {
"form":form,
"instance":instance,
}
return render(request, "index.html", context)
settings.py
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, "Static")
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, "Media")
index.html
{% if instance.image %}
<img src="{{instance.image.url}}" alt="Image"/>
{% endif %}
ERROR: After uploading an image named <something>.jpg, if I visit, 127.0.0.1:8000/media/1.jpeg, browser does not displays image, instead it shows index.html page.
SO how to serve this media file correctly?
This line is a catch-all for every URL:
url(r'', include("Image.urls")),
Without seeing the contents of Image/urls.py I can only suggest replacing that line with an explicit pattern that executes the index view, such as:
url(r'^$', my_index_view),
According to the code the image should be displayed on the index.html template but there seems to be some problem with the img src
My models.py
from django.db import models
class Rockinfo(models.Model):
rock_name = models.CharField(max_length=200,default="ac/dc")
rock_img = models.ImageField(upload_to="%Y/%m/%d",default="1992/08/92")
rank = models.IntegerField(default=0)
def __str__(self):
return self.rock_name
My admin.py
from django.contrib import admin
from .models import Rockinfo, Rockvids
class ChoiceInline(admin.TabularInline):
model = Rockvids
extra = 10
class RockinfoAdmin(admin.ModelAdmin):
fieldsets = [
('The Fucking Band', {'fields': ['rock_name']}),
('Image', {'fields': ['rock_img']}),
]
inlines = [ChoiceInline]
list_display = ('rock_name', 'rock_img')
list_filter = ['rank']
search_fields = ['rock_name']
admin.site.register(Rockinfo, RockinfoAdmin)
my application's urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.IndexView.as_view(), name='index'),
]
My project's models.py
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^rockinglist/', include('rockinglist.urls', namespace="rockinglist")),
url(r'^admin/', include(admin.site.urls)),
]
My views.py file
from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from django.views import generic
from .models import Rockvids, Rockinfo
class IndexView(generic.ListView):
template_name = 'rockinglist/index.html'
context_object_name = 'latest_rockinfo_list'
def get_queryset(self):
return Rockinfo.objects.order_by('-rank')[:5]
The index.html file
{% if latest_rockinfo_list %}
<ul>
{% for rockinfo in latest_rockinfo_list %}
<h1>{{ rockinfo.rock_name }}</a></li>
<img src="img\{{ rockinfo.rock_img }}" alt="ac/dc">
{% endfor %}
</ul>
{% else %}
<p>No</p>
{% endif %}
I think the problem is with the root of the image.Somehow django cannot reach the images.I want to display the rock_name along with the associated rock_img. Can someone help me figure this out.Thanks in advance.
In your project's urls.py, add this:
# your other imports here ...
# ...
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLs ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
In your settings.py file, make sure you have this:
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
In your templates:
<img src="{{ rockinfo.rock_img.url }}" alt="ac/dc">
Note: If BASE_DIR is not defined in your settings, put this on top of your settings file:
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
First of all check if MEDIA_URL is provided in you settings. Django doesn't server media during development so you have to have the following in your project's urls.py:
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
after this you can access your image in template with
{{ rockinfo.rock_img.url }}