ImageField in Django - python

I am attempting to build a basic database of song information, regarding artists, songs and albums. On my page for any given album I am attempting to display the album art for a given album. I am using the built-in image upload feature within Django Admin to upload the images. The images urls are being saved correctly within mysql (I checked), but the images are not being displayed on the site. From what I have read online the possible problematic areas are either in the URLs file(which I have not modified to accommodate media) or in my MEDIA_URL, but I have followed instructions as Django has outlined. Below I am linking the code I think is relevant. Thank you in advance for the help!
views.py
from django.shortcuts import render_to_response
from django.template import RequestContext
from Radio.models import Song, Artist, Album
def SongsAll(request):
songs = Song.objects.all().order_by('songName')
context = {'songs' : songs}
return render_to_response('songsall.html', context, context_instance = RequestContext(request))
def SpecificSong(request, songname):
song = Song.objects.get(songName = songname)
context = {'song':song}
return render_to_response('specificsong.html',context, context_instance=RequestContext(request))
def SpecificArtist(request, artistname):
singer = Artist.objects.get(artistName = artistname)
songs = Song.objects.filter(artist = singer)
context = {'songs':songs}
return render_to_response('specificartist.html',context, context_instance=RequestContext(request))
def SpecificAlbum(request, albumname):
album = Album.objects.get(albumName = albumname)
songs = Song.objects.filter(album = album)
context = {'songs':songs}
return render_to_response('specificalbum.html', context, context_instance=RequestContext(request))
settings.py (only the relevant parts)
MEDIA_ROOT = '/home/kyle/Downloads/Django-1.5.1/radioSite/media/'
MEDIA_URL = 'http://127.0.0.1:8000/media/'
models.py
from django.db import models
class Artist(models.Model):
artistName = models.CharField(max_length = 30)
artistInfo = models.TextField()
def __unicode__(self):
return self.artistName
class Album(models.Model):
albumName = models.CharField(max_length = 30)
artist = models.ForeignKey('Artist')
date = models.DateTimeField('Release Date')
albumInfo = models.TextField()
albumArt = models.ImageField(upload_to="images/albumart/")
def __unicode__(self):
return self.albumName
class Song(models.Model):
songName = models.CharField(max_length = 30)
artist = models.ForeignKey('Artist')
album = models.ForeignKey('Album')
def __unicode__(self):
return self.songName
base.html
<html>
<head>
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}css/Radio.css"/>
{% block extended %}{% endblock %}
</head>
<body>
<div id="pageContainer">
{% block content %}
{% endblock %}
</div>
</body>
</html>
specificalbum.html
{% extends "base.html" %}
{% block content %}
<div id="singlealbum">
<p><img src="{{ songs.0.album.albumart.url }}"/>Name: {{ songs.0.album }}</p>
<p>Artist:{{ songs.0.artist }}</a></p>
<p>Song list:</p>
{% for song in songs %}
<p>{{ song }}</p>
{% endfor %}
</div>
{% endblock %}

Are your images actually getting uploaded somewhere where a web server is expecting to serve them?
From your MEDIA_URL setting I'm guessing that you're trying to get the Django server to serve the images. You can check the documentation for how to do this during development, or if you're just learning Django, but please don't try to do this for anything at all serious - you'll be much better served by using a dedicated web server like Apache or the like.

Related

Django failing to load images from my media file but is not giving me a 404 error and has the correct file path. What could be causing this issue?

To clarify my title, I have a database set up in my Django application that takes information from albums, including album covers. The image saves in the database, goes to the correct MEDIA_ROOT specified in my settings.py file, and shows the correct url path when checking the request path. I am using the latest version of Django and have Pillow installed to add the images into the database through the admin site.
Previously, when the file path was wrong, Django served a 404 error and couldn't find the file. Now that the path is correct, it loads for a moment and then says "server not found". When I inspect the image, it says that the "connection used to fetch this resource was not secure." however I am running the server locally and am not in a production enviroment, and all answers related to this issue seem to come from running the server in production.
When I attempt to open the image in a new tab, the tab says "Server not found" after attempting to load the filepath: "http://albums/filename_oja97pG.png" (you can see here the unsercure http response. I replaced the file name for privacy reasons.)
I am unsure what would be causing this issue. Here is my code:
models.py
class Album(models.Model):
title = models.CharField(
max_length=200,
validators=[MinLengthValidator(2, "Must be at least two characters.")]
)
release_date = models.DateField()
picture = models.ImageField(upload_to='albums/', blank=True)
content_type = models.CharField(max_length=256, blank=True, help_text='The MIMEType of the file')
description = models.TextField(blank=True)
def __str__(self):
return self.title
settings.py
BASE_DIR = Path(__file__).resolve().parent.parent
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media').replace('\\', '/')
urls.py
urlpatterns = [
path('', views.MusicView.as_view(), name='music'),
path('albums/<int:album_id>', views.AlbumView.as_view(), name='album_detail'),
]
projects urls.py
...
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
views.py
class AlbumView(DetailView):
model = Album
template_name = 'music/album_detail.html'
def get(self, request, album_id):
al = Album.objects.get(pk=album_id)
if al is not None:
context = {
'album' : al,
}
return render(request, self.template_name, context)
else:
raise Http404('Album does not exist.')
html template being served
{% extends 'base.html' %}
{% block welcome %}
{{ album.title }}
{% if album.content_type %}
<img src="/{{ BASE_DIR }}/{{ album.picture }}">
{% endif %}
{% endblock %}
Thanks for the help. Let me know what other information I can provide. I have attempted to load in other borwsers and have gotten the same problem.
You can try to use the url directly from the ImageFile field, so in your template:
{% extends 'base.html' %}
{% block welcome %}
{{ album.title }}
{% if album.content_type %}
<img src="{{ album.picture.url }}">
{% endif %}
{% endblock %}

Django: Problem with Getting The Right Objects

I am a beginner learning Django through a building an app, called PhoneReview. It will store reviews related to the latest mobile phone. It will also display phone brands, along with the associated phone models and their reviews.
Right now, I am facing a problem. I have added two phone brands, Samsung and Apple, through Django admin. They are being displayed at http://127.0.0.1:8000/index.
When I click on Samsung, I see three phone models, Galaxy S10, Galaxy Note 10 and iPhone 11, which have already been added through Django admin. However, iPhone 11 is not supposed to be displayed here, as its brand is Apple, not Samsung. So, basically, when I click on Samsung, only Galaxy S10 and Galaxy Note 10 are supposed to be displayed, not iPhone 11.
How can I fix the issue?
Here are my codes of models.py located inside PhoneReview folder:
from django.db import models
from django.template.defaultfilters import slugify
# Create your models here.
class Brand(models.Model):
brand_name = models.CharField(max_length=100)
origin = models.CharField(max_length=100)
manufacturing_since = models.CharField(max_length=100, null=True, blank=True)
def __str__(self):
return self.brand_name
def save(self, *args, **kwargs):
self.slug = slugify(self.brand_name)
super().save(*args, **kwargs)
class PhoneModel(models.Model):
brand = models.ForeignKey(Brand, on_delete=models.CASCADE)
model_name = models.CharField(max_length=100)
launch_date = models.CharField(max_length=100)
platform = models.CharField(max_length=100)
def __str__(self):
return self.model_name
class Review(models.Model):
phone_model = models.ManyToManyField(PhoneModel, related_name='reviews')
review_article = models.TextField()
date_published = models.DateField(auto_now=True)
# slug = models.SlugField(max_length=150, null=True, blank=True)
link = models.TextField(max_length=150, null=True, blank=True)
def __str__(self):
return self.review_article
Here are my codes of urls.py located inside PhoneReview folder:
from . import views
from django.urls import path
urlpatterns = [
path('index', views.BrandListView.as_view(), name='brandlist'),
path('phonemodel/<int:pk>/', views.ModelView.as_view(), name='modellist'),
path('details/<int:pk>/', views.ReviewView.as_view(), name='details'),
]
Here are my codes of views.py located inside PhoneReview folder:
from django.shortcuts import render
from django.views import generic
from .models import Brand, PhoneModel, Review
class BrandListView(generic.ListView):
template_name = 'PhoneReview/index.html'
context_object_name = 'all_brands'
def get_queryset(self):
return Brand.objects.all()
class ModelView(generic.ListView):
template_name = 'PhoneReview/phonemodel.html'
context_object_name = 'all_model_name'
def get_queryset(self):
return PhoneModel.objects.all()
class ReviewView(generic.DetailView):
model = Review
template_name = 'PhoneReview/details.html'
Here are my codes of apps.py located inside PhoneReview folder:
from django.apps import AppConfig
class PhonereviewConfig(AppConfig):
name = 'PhoneReview'
Here are my codes of index.html located inside templates folder:
{% extends 'PhoneReview/base.html' %}
{% load static %}
{% block title%}
Brand List
{% endblock %}
{% block content %}
<!--Page content-->
<h1>This is Brand List Page</h1>
<h2>Here is the list of the brands</h2>
<ul>
{% for brand in all_brands %}
<!-- <li>{{ brand.brand_name }}</li>-->
<li>{{ brand.brand_name }}</li>
{% endfor %}
</ul>
<img src="{% static "images/brandlist.jpg" %}" alt="Super Mario Odyssey" /> <!-- New line -->
{% endblock %}
Here are my codes of phonemodel.html located inside templates folder:
{% extends 'PhoneReview/base.html' %}
{% load static %}
{% block title%}
Phone Model Page
{% endblock %}
{% block content %}
<!--Page content-->
<h1>This is Phone Model Page</h1>
<h2>Here is the phone model</h2>
<ul>
{% for phonemodel in all_model_name %}
<li>{{ phonemodel.model_name }}</li>
{% endfor %}
</ul>
<img src="{% static "images/brandlist.jpg" %}" alt="Super Mario Odyssey" /> <!-- New line -->
{% endblock %}
Here are my codes of details.html located inside templates folder:
{% extends 'PhoneReview/base.html' %}
{% load static %}
<html>
<link rel="stylesheet" type="text/css" href="{% static "css/style.css" %}">
<html lang="en">
{% block title%}Details{% endblock %}
{% block content %}
<h1>This is the Details Page</h1>
<h2>Review:</h2>
<p>{{ review.review_article }}</p>
<h2>News Link:</h2>
<p>{{ review.link }}</p>
{% endblock %}
</html>
Have I done anything wrong in views.py?
Change your list view see this
class ModelView(generic.ListView):
template_name = 'PhoneReview/phonemodel.html'
context_object_name = 'all_model_name'
def get_queryset(self):
self.brand = get_object_or_404(Brand, pk=self.kwargs['pk'])
return PhoneModel.objects.filter(brand=self.brand)

Django: Problem with Adding Clickable Link in the Second Template

I am a beginner in Django. I am building a Django app, named PhoneReview. It will store reviews related to the latest mobile phone. It will also display phone brands, along with the associated phone models.
I have already created models and views. I have also managed to add clickable link in the first template (brandlist.html). In the first template, when you click on the brand name, like Samsung, you will be taken to the page of the phone model, like Galaxy S10.
Here is the screenshot of the first template:
When you click the link, you will be taken to the second template (phonemodel.html). But now, I am facing an issue. There is no clickable link on the phone model ("Galaxy S10") that will direct you to details.html. Here is the screenshot.
Here are the codes of models.py inside the "PhoneReview" folder:
from django.db import models
from django.template.defaultfilters import slugify
# Create your models here.
class Brand(models.Model):
brand_name = models.CharField(max_length=100)
origin = models.CharField(max_length=100)
manufacturing_since = models.CharField(max_length=100, null=True, blank=True)
def __str__(self):
return self.brand_name
def save(self, *args, **kwargs):
self.slug = slugify(self.brand_name)
super().save(*args, **kwargs)
class PhoneModel(models.Model):
brand = models.ForeignKey(Brand, on_delete=models.CASCADE)
model_name = models.CharField(max_length=100)
launch_date = models.CharField(max_length=100)
platform = models.CharField(max_length=100)
def __str__(self):
return self.model_name
class Review(models.Model):
phone_model = models.ManyToManyField(PhoneModel, related_name='reviews')
review_article = models.TextField()
date_published = models.DateField(auto_now=True)
slug = models.SlugField(max_length=150, null=True, blank=True)
def __str__(self):
return self.review_article
Here are the codes of urls.py inside the "PhoneReview" folder:
from . import views
from django.urls import path
urlpatterns = [
path('index', views.BrandListView.as_view(), name='brandlist'),
path('phonemodel/<int:pk>/', views.ModelView.as_view(), name='modellist'),
path('details/<int:pk>/', views.ReviewView.as_view(), name='details'),
]
Here are the codes of views.py inside the "PhoneReview" folder:
from django.views import generic
from .models import Brand, PhoneModel, Review
class BrandListView(generic.ListView):
template_name = 'PhoneReview/brandlist.html'
context_object_name = 'all_brands'
def get_queryset(self):
return Brand.objects.all()
class ModelView(generic.DetailView):
model = PhoneModel
template_name = 'PhoneReview/phonemodel.html'
class ReviewView(generic.DetailView):
model = Review
template_name = 'PhoneReview/details.html'
Here are the codes of apps.py inside the "PhoneReview" folder:
from django.apps import AppConfig
class PhonereviewConfig(AppConfig):
name = 'PhoneReview'
Here are the codes of details.html inside the "templates" folder:
{% extends 'PhoneReview/base.html' %}
{% load static %}
<html>
<link rel="stylesheet" type="text/css" href="{% static "css/style.css" %}">
<html lang="en">
{% block title%}Details{% endblock %}
{% block content %}
<h1>This is the Details Page</h1>
<h2>Review:</h2>
<p>{{ review.review_article }}</p>
<h2>News Link:</h2>
<p>{{ review.slug }}</p>
{% endblock %}
</html>
Here are the codes of phonemodel.html inside the "templates" folder:
{% extends 'PhoneReview/base.html' %}
{% load static %}
{% block title%}
Phone Model Page
{% endblock %}
{% block content %}
<!--Page content-->
<h1>This is Phone Model Page</h1>
<h2>Here is the phone model</h2>
<ul>
<li>{{ phonemodel.model_name }}</li>
</ul>
<img src="{% static "images/brandlist.jpg" %}" alt="Super Mario Odyssey" /> <!-- New line -->
{% endblock %}
I tried replacing <li>{{ phonemodel.model_name }}</li> with <li>{{ phonemodel.model_name }}</li>. But I get an error, which looks like this:
NoReverseMatch at /phonemodel/1/
Reverse for 'details' with arguments '('',)' not found. 1 pattern(s) tried: ['details/(?P<pk>[0-9]+)/$']
How can I fix the issue?
There is no context variable named brand and you don't need it anyway. You should use the id of the phonemodel:
<li>
<a href = "{% url 'details' phonemodel.id %}">
{{ phonemodel.model_name }}
</a>
</li>

Images from Model in HTML Django 1.10

I am new to Django (1.10) so please excuse me. I am trying to visualise images from my model Clothes. Trying to create some sort of small webshop to train.
My Model:
from __future__ import unicode_literals
from django.db import models
from django.utils import timezone
class Clothes(models.Model):
user = models.ForeignKey('auth.User')
title = models.CharField(max_length=200)
description = models.TextField()
image = models.ImageField(upload_to = '/pic_folder/', default = '/pic_folder/None/no-img.jpg')
type_clothes = models.CharField(max_length=100)
created_date = models.DateTimeField(
default=timezone.now)
published_date = models.DateTimeField(
blank=True, null=True)
class Meta:
verbose_name = "Kleding"
verbose_name_plural = "Kleding"
def publish(self):
self.published_date = timezone.now()
self.save()
def __str__(self):
return self.title
Views.py
from django.shortcuts import render
from django.utils import timezone
from .models import Clothes
def clothes_overview(request):
clothes= Clothes.objects.filter(published_date__lte=timezone.now())
return render(request, 'Clothes/clothes_overview.html', {'clothes' : clothes})
clothes_overview.html
{% load staticfiles %}
<html>
<head>
<title>WebShop</title>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">
<link rel="stylesheet" href="{% static 'css/clothes.css' %}">
</head>
<body>
<div>
<h1>Clothing WebShop</h1>
</div>
{% for cloth in clothes %}
<div>
<p>published: {{ cloth.published_date }}</p>
<h1>{{ cloth.title }}</h1>
// DISPLAY IMAGE HERE
<p>{{ cloth.text|linebreaksbr }}</p>
</div>
{% endfor %}
</body>
</html>
I have tried one option which I came across by searching Stack:
<img src="{{ cloth.image.url }}">
This helped others but still left my page showing broken images. I looked in the source using Google Chrome and found that the path is (specific for the hoodie.jpg):
<img src="pic_folder/hoodie.jpg">
I then tried another method:
<img src="{% static 'pic_folder/image.jpg' %}">
This did show the image.jpg in my browser multiple times! The path which I found is:
<img src="/static/pic_folder/image.jpg">
I somehow need to combine these two methods so that the images are loaded dynamically into the webpage. Could someone help me?
Djangos static template tag, allows you to pass in variables, so as you suggest - combine your approaches
<img src="{% static cloth.image.url %}">

How do I implement markdown in Django 1.6 app?

I have a text field in models.py where I can input text content for a blog using the admin.
I want to be able to write the content for this text field in markdown format, but I'm using Django 1.6 and django.contrib.markup is not supported anymore.
I can't find anywhere that has a tutorial and runs through adding markdown to a text field in Django 1.6. Can someone look at my .py files and help me implement markdown to my app.
models.py
from django.db import models
# Create your models here.
class Post(models.Model):
title = models.CharField(max_length=200)
pub_date = models.DateTimeField()
text = models.TextField()
tags = models.CharField(max_length=80, blank=True)
published = models.BooleanField(default=True)
admin.py
from django.contrib import admin
from blogengine.models import Post
class PostAdmin(admin.ModelAdmin):
# fields display on change list
list_display = ['title', 'text']
# fields to filter the change list with
save_on_top = True
# fields to search in change list
search_fields = ['title', 'text']
# enable the date drill down on change list
date_hierarchy = 'pub_date'
admin.site.register(Post, PostAdmin)
index.html
<html>
<head>
<title>My Django Blog</title>
</head>
<body>
{% for post in post %}
<h1>{{ post.title }}</h1>
<h3>{{ post.pub_date }}</h3>
{{ post.text }}
{{ post.tags }}
{% endfor %}
</body>
</html>
Thank you for your answers and suggestions, but I've decided to use markdown-deux.
Here's how I did it:
pip install django-markdown-deux
Then I did pip freeze > requirements.txt to make sure that my requirements file was updated.
Then I added 'markdown_deux' to the list of INSTALLED_APPS:
INSTALLED_APPS = (
...
'markdown_deux',
...
)
Then I changed my template index.html to:
{% load markdown_deux_tags %}
<html>
<head>
<title>My Django Blog</title>
</head>
<body>
{% for post in post %}
<h1>{{ post.title }}</h1>
<h3>{{ post.pub_date }}</h3>
{{ post.text|markdown }}
{{ post.tags }}
{% endfor %}
</body>
</html>
Ah, I met with the same problem several months ago, and I found the easiest and most robust solution is to use Github Markdown API.
Here is the code I use for my blog, which I believe will help you more or less. btw I use Python 3 so the encoding part may be different from Python 2.
# generate rendered html file with same name as md
headers = {'Content-Type': 'text/plain'}
if type(self.body) == bytes: # sometimes body is str sometimes bytes...
data = self.body
elif type(self.body) == str:
data = self.body.encode('utf-8')
else:
print("somthing is wrong")
r = requests.post('https://api.github.com/markdown/raw', headers=headers, data=data)
# avoid recursive invoke
self.html_file.save(self.title+'.html', ContentFile(r.text.encode('utf-8')), save=False)
self.html_file.close()
My code is hosted on github, you can find it here
And My blog is http://laike9m.com.
You may use substitution of old markup implemented here - https://github.com/jamesturk/django-markupfield

Categories