I'm trying to write a simple blog using a Django framework. I want to have a cover image for a every post.
I uploaded an image via Admin site and everything seems to be fine but image is not rendering in a browser.
Here is my files:
models.py
(...)
class Post(models.Model):
author = models.ForeignKey('Author', on_delete=models.CASCADE)
title = models.CharField(max_length=250)
slug = models.SlugField(unique=True, blank=True, max_length=250)
created = models.DateTimeField(auto_now=False, auto_now_add=True)
modified = models.DateTimeField(auto_now=True, auto_now_add=False)
image = models.ImageField(upload_to="images/%Y/%m/", blank=True, null=True)
content = models.TextField()
(...)
django_blog_project\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('blog.urls')),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
blog\urls.py
(...)
urlpatterns = [
url(r'^posts/create/$', PostCreate.as_view(), name="post_create"),
url(r'^posts/([\w-]+)/$', AuthorPostList.as_view(), name="posts_by_author"),
url(r'^(?P<slug>[-\w]+)/$', PostDetailView.as_view(), name="post_detail"),
url(r'^', PostListView.as_view(), name="post_list"),
]
settings.py
(...)
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
(...)
post_detail.html
{% extends "blog/base.html" %}
{% block content %}
<h1>{{ post.title }}</h1>
<img src="{{ post.image.url }}" >
<p>{{ post.content }}</p>
<p>Autor: {{ post.author }}</p>
<p>Opublikowano: {{ post.modified }}</p>
{% endblock %}
Dir tree
My directory tree
URL of the image resolving to
<img src="/media/images/2016/12/fotolia_97812586.jpg">
Adding $ char in pattern solved a problem.
blog\urls.py
(...)
urlpatterns = [
url(r'^posts/create/$', PostCreate.as_view(), name="post_create"),
url(r'^posts/([\w-]+)/$', AuthorPostList.as_view(), name="posts_by_author"),
url(r'^(?P<slug>[-\w]+)/$', PostDetailView.as_view(), name="post_detail"),
# url(r'^', PostListView.as_view(), name="post_list"), # WRONG!
url(r'^$', PostListView.as_view(), name="post_list"), # CORRECT!
]
Related
my image file is not loading in webpage it is showing The 'Img' attribute has no file associated with it
models.py
class Post(models.Model):
title = models.CharField(max_length=200, unique=True)
slug = models.SlugField(max_length=100,unique=True)
author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='blog_posts')
updated_on = models.DateTimeField(auto_now= True)
content = models.TextField()
created_on = models.DateTimeField(default=timezone.now())
status = models.IntegerField(choices=STATUS, default=0)
Img = models.ImageField(null =True, blank = True, upload_to='static/images')
class Meta:
ordering = ['-created_on']
def __str__(self):
return self.title
urls.py
from django.contrib import admin
from django.conf.urls import include
from django.urls import path
from portfo import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('', views.firstpage,name='firstpage'),
path('', include('portfo.urls')),
path('admin/', admin.site.urls),
] + static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR,"static")
]
MEDIA_URL ="/images/"
MEDIA_ROOT=os.path.join(BASE_DIR,'static/images')
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
template
{% for post in posts %}
<div class="card mb-4">
<div class="card-body " style="background-color: #F2F4F3;">
<img src="{{post.Img.url}}" />
<h2 class="card-title" style="margin-left:40% ;">{{ post.title|capfirst }}</h2>
<p class="card-text text-muted h6">{{ post.author }} | {{ post.created_on}} </p>
<p class="card-text">{{post.content|slice:":200" }}...</p>
Read More
</div>
</div>
{% endfor %}
I have a file name images inside the static. Your help is much appriciated
I have a record label website im building and I want to populate a navbar dropdown list with artists from the Artst object Artist.objects.all().
I have it working in one app "music" but only when I append "/artistlist/" onto the end. Any other URL doesnt populate the list.
I want the list to always be there as its a navbar item. At the moment I am trying to get a context_processors.py working.
youtube tutorial im following for the exactsame issue
I could use some help as I'm clearly doing something stupid, or overlooked something basic. On all other urls it triggers the else I added "We currently dont have any artists yet..".
Hope it makes sense to someone. Any help is greatly appreciated.
base.html
<div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
<div class="dropdown-item" href="#">
{% if all_artists %}
<ul>
{% for artist in all_artists %}
<li class="dropdown-item">
<a href="{% url 'music:artist' artist.id %}">
<img src="{{ artist.artist_logo.url }}" style="width: 100px"><br>
{{ artist.artist_name }}<br>
{{ artist.artist_url }}<br>
</a>
</li>
{% endfor %}
</ul>
{% else %}
<h3>We currently dont have any artists yet..</h3>
{% endif %}
</div>
</div>
main urls.py
from django.contrib import admin
from django.urls import include, path, re_path
from django.conf import settings
from . import views
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
# include urls from the music app
path('music/', include('music.urls', namespace='music')),
# path('', include('music.urls', namespace='home')),
path('', include('blog.urls', namespace='blog')),
# path('single', include('blog.urls', namespace='single')),
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
music/models.py
from django.db import models
# Create your models here.
class Artist(models.Model):
artist_name = models.CharField(max_length=250, default='')
artist_logo = models.FileField()
artist_url = models.URLField(blank=True)
def __str__(self):
return self.artist_name
class Release(models.Model):
artist = models.ForeignKey(Artist, on_delete=models.CASCADE)
release_title = models.CharField(max_length=500)
release_cover = models.FileField()
release_duration = models.IntegerField()
def __str__(self):
return self.release_title
class Track(models.Model):
release = models.ForeignKey(Release, default='', on_delete=models.CASCADE)
artist = models.ForeignKey(Artist, default='', on_delete=models.CASCADE)
track_title = models.CharField(max_length=200)
track_version = models.CharField(max_length=200)
track_genre = models.CharField(max_length=100)
track_duration = models.IntegerField()
track_number = models.SmallIntegerField()
class Meta:
ordering = ["track_number"]
def __str__(self):
return self.track_title
app_name = 'music'
music/urls.py
from django.contrib import admin
from django.urls import path, include, re_path
from . import views
# from blog.views import newsfeed, single
urlpatterns = [
# no info past music return index EG /music/
path('', views.IndexView.as_view(), name='index'),
# re_path(r'^$', views.IndexView.as_view(), name='index'),
# Releases
# albums/releases
re_path(r'^release/$', views.ReleaseView.as_view(), name='release'),
# looking for music page with album id afterwards /music/1
re_path(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name="detail"),
# Artists
re_path(r'^artistlist.html$', views.ArtistListView.as_view(), name='artistlist'),
re_path(r'^(?P<pk>[0-9]+)/$', views.ArtistView.as_view(), name="artist"),
# Register
# register url
re_path(r'^register/$', views.UserFormView.as_view(), name="register"),
]
# defined the app name in case the same fields are used in other apps
app_name = 'music'
music/context_processors.py
from .models import Artist
def all_artists(request):
artist = Artist.objects.all()
return {'artist':artist}
I found this vieo which is exactly the same issue, and tried adjusting the context processor to te above, and also tried just:
from music.models import Artist:
settings.py
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')]
,
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'music.context_processors.all_artists',
],
},
},
]
the only thing you want to do is change the return key value to all_artists because you fetch all data through all_artists key in your base.html but according to your code there is not any all_artists found do change in the last line in context_processor.py and you are good to go
music/context_processors.py
from .models import Artist
def all_artists(request):
artist = Artist.objects.all()
return {'all_artists':artist}
Does not display an image!
image is exists, dut django didn't display any images on page, how to fix this?
this is my models.py
class All_Images_Of_The_Series(models.Model):
to_series = models.ForeignKey(Series, on_delete=models.CASCADE, blank=True, default=None)
image_of_all = models.ImageField(upload_to="previews/previews_for_series/", default=None,width_field="width_field", height_field="height_field")
is_poster = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
width_field = models.IntegerField(default=0)
height_field = models.IntegerField(default=0)
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
updated = models.DateTimeField(auto_now_add=False, auto_now=True)
def __str__(self):
return "Active: |%s| and Poster: |%s| " % (self.is_active, self.is_poster)
class Meta:
ordering = ["-timestamp"]
verbose_name = 'All_Images_of_the_Series'
verbose_name_plural = 'All_Images_of_the_Series'
this is my views.py
def homeview(request, *args, **kwargs):
full_path = All_Images_Of_The_Series.objects.all()
context = {"full_path":full_path,}
return render(request, 'home.html', context)
this is my template
<div class="col-sm-3 right-side">
<div class="new-movies-block">
<a class="header" href="#/new/">
<div class="title">Новинки</div>
</a>
{% for one_to_one_path in full_path %}
<div class="movie-spacer" ></div>
<a class="new-movie" href="{{ one_to_one_path.to_series.get_absolute_url }}" title="{{ one_to_one_path.to_series.eng_name }}">
<div class="title-info">
{{ one_to_one_path.to_series.season_of_this_series.number_of_season }} сезон {{ one_to_one_path.to_series.number_of_series }} серия
</div>
<div class="date">{{ one_to_one_path.to_series.timestamp_rus }}</div>
<img src="{{ one_to_one_path.image_of_all.url }}" class="img-responsive">
</a>
{% endfor %}
</div>
</div>
If you look at the element code, the images, then in the line "src" there is a path to the picture, and it's working! But does not display the picture itself!
<img src="/media/previews/previews_for_series/1.png" class="img-responsive">
this is error in console(f12)
GET http://127.0.0.1:8000/media/previews/previews_for_series/1.png 404 (Not Found)
Do this !
from django.conf.urls import include, url
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'^series/', include("serials.urls", namespace='series')),
url(r'^', include("serials.urls", namespace='homeview')),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
just a quick thoughts, you don't show me the things you might need to work. For example if this if for development on the urls you need this https://docs.djangoproject.com/en/1.11/howto/static-files/#serving-files-uploaded-by-a-user-during-development and on your settings you may need something like that
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
I hope it helps
Best
Perhaps you haven't added the media to your urls.py
From django.conf import settings
# your stuff
if settings.DEBUG:
urlpatterns += patterns('',
(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT
})
)
I am following a Django book which builds a web application. When I build a template, I get the same result as that of the book, except for my images - they are not there.
I am wondering what can be causing this issue. The images have correct URL's but when I try to open them, Django states "Page NOT found 404".
I am pasting the relevant code below. In addition, I include a screenshot of my directory tree.
shop/models.py:
class Product(models.Model):
category = models.ForeignKey(Category,
related_name='products')
name = models.CharField(max_length=200, db_index=True)
slug = models.SlugField(max_length=200, db_index=True)
image = models.ImageField(upload_to='products/%Y/%m/%d',
blank=True)
description = models.TextField(blank=True)
price = models.DecimalField(max_digits=10, decimal_places=2)
stock = models.PositiveIntegerField()
available = models.BooleanField(default=True)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
template:
<a href="{{ product.get_absolute_url }}">
<img src=" {% if product.image %}
{{ product.image.url }}
{%else %}
{% static 'img/no_image.png' %}
{% endif %}
">
</a>
views.py
def product_list(request, category_slug=None):
category = None
categories = Category.objects.all()
products = Product.objects.filter(available=True)
if category_slug:
category = get_object_or_404(Category, slug=category_slug)
products = products.filter(category=category)
return render(request, 'shop/product/list.html',
{'category': category,
'categories': categories,
'products': products})
Edit (settings.py and urls.py):
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.10/howto/static-files/
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
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'^shop/', include('shop.urls', namespace='shop')),
url(r'^cart/', include('cart.urls', namespace='cart')),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
I have images I uploaded through django admin, but they are not displaying. The weird thing is that I have another project with the EXACT same code and it works. object.image.url outputs /media/media/image.jpg as does my other project. But this project does not show the image. if I put an image from my static folder or if I hardcode an image, it works fine. The problem is only when I try an image uploaded from the admin it does not work. Am I missing something in my settings.py file? or anywhere?
Models.py:
from django.db import models
# Create your models here.
class Connect(models.Model):
title = models.CharField(max_length=70)
short_description = models.TextField(null=True, blank=True)
description = models.TextField()
image = models.ImageField(upload_to='media', blank=True, null=True)
def __str__(self):
return self.title
views.py:
def index(request):
about = About.objects.all()
staff = Staffmembers.objects.all()
ministries = Ministries.objects.all()
connect = Connect.objects.all()
context = {
'template': 'home',
'connect': connect,
'about': about,
'staff': staff,
'ministries': ministries,
}
return render(request,'home/index.html', context)
template(index.html):
<div class="connect-wrapper row">
<h1 class="title connect-title">Connect</h1>
{% for object in connect %}
<div class="home-div connect-div col-md-4">
<h4>{{ object.title }}</h4>
<p>{{ object.short_description }}</p>
{% if object.image %}
<img class="connect-image-home" src="{{object.image.url}}" alt="connect">
<p>{{object.image.url}}</p> //sanity check
{% endif %}
</div>
{% endfor %}
</div>
settings.py:
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
urls.py:
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', include('home.urls'), name="home"),
]
I believe you need to add the media urls to your urls.py. Something like:
from django.conf import settings
from django.conf.urls import url
from django.conf.urls.static import static
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', include('home.urls'), name="home"),
] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
On production environment Django does not load the media root automatically so that we can we can overcome that issue by adding following after url patterns:
urlpatterns = [
''''
your urls
''''
] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
If you are using more than one app and including app urls on main app url, just add this on main project url.