Issue with images in Django - python

Have an issue with images form in Django.
Upload of images is working correctly and displayed in admin page also right.
But if I want to use this image in my templates or go direct by the link from admin console, receiving 404 error, why?
Django : 2.1.1
Python : 3.6.6
models.py
from art.settings import STATICFILES_DIRS
import os
def get_image_path(instance, filename):
return os.path.join(STATICFILES_DIRS[0], 'collections', filename)
class ArtCollections(models.Model):
title = models.CharField(max_length=200)
content = models.TextField()
class ImagesList(models.Model):
collection_id = models.ForeignKey(ArtCollections, on_delete=models.CASCADE, default=1)
images = models.ImageField(upload_to=get_image_path, blank=True, null=True)
From admin console, uploading the file, and its doing in correct folder, exx /static/image.jpg
file is exist :
-rw-r--r-- 1 www-data www-data 438930 Dec 2 /static/image.jpg
but still getting 404
P.S. on folder give full grants and for apache also
template ex :
{% block content %}
{{ count }}
{% for image in collection_images %}
<img src="{{ image.images }}">
{% endfor %}
{% endblock %}

you need to add url at the end of images in template:
{% block content %}
{{ count }}
{% for image in collection_images %}
<img src="{{ image.images.url }}">
{% endfor %}
{% endblock %}

Related

Content not visible on webpage

I am creating a database website with python and django. My problem is that the content I try to get data from my class' fields doesn't appear on the id-page on django. I am able to make a successful search, and I get links for my searches. The name-field is visible in searches and on the page, but nothing else appears. When I click on the link, I go to luokka_id/number. I must be missing something but can't figure out what the problem is.
models.py
class luokka(models.Model):
nimi = models.CharField('Pääkäyttöluokka', max_length=100)
vara = models.CharField('Varakäyttöluokka', max_length=100)
varaaja = models.CharField('Varakäyttöluokka', max_length=100)
def __str__(self):
return self.nimi
and on the näytä_luokka.html (show class):
{% extends 'tietokanta/base.html' %}
{% block content %}
<center>
{{luokkalistaus}}
{{luokka}}
{{ luokka.nimi }}
{{ luokka.vara }}
{{ luokka.varaaja }}
</center>
{% endblock %}
and views.py:
def näytä_luokka(request, luokka_id):
luokkalistaus = luokka.objects.get(pk=luokka_id)
return render(request, 'tietokanta/näytä_luokat.html',
{'luokkalistaus': luokkalistaus})
I don't get any errors to help me out here. It's just an empty page, but it should show some extra data.
You have named the key of context as luokkalistaus not luokka, so the template should be:
{% extends 'tietokanta/base.html' %}
{% block content %}
<center>
{{ luokkalistaus.nimi }}
{{ luokkalistaus.vara }}
{{ luokkalistaus.varaaja }}
</center>
{% endblock %}

How Do I Get Django to Show Image Field From Model in Templates?

I am trying to get the uploaded image to show in the project template. Here is what my code looks like currently:
projects.html
{% extends "base.html" %}
{% block content %}
<h1>{{ project.title }} HELLO</h1>
<div class="content-section">
<div class="media">
<img src="{{ project.image.url }}" alt="beach" width=250px height=250px />
</div>
<div>
<h5>About the project:</h5>
<p>{{ project.description }}</p>
<br>
<h5>Technology used:</h5>
<p>{{ project.tools }}</p>
</div>
</div>
{% endblock content %}
models.py
class Project(models.Model):
title = models.CharField(max_length=500, unique=True)
description = models.TextField(max_length=500)
tools = models.CharField(max_length=200)
image = models.ImageField(default='default.jpg', upload_to="beach_photos", blank=True)
def __str__(self):
return f'{self.title}'
views.py
from django.shortcuts import render
from django.http import HttpResponse
from projects.models import Project
def projects(request):
project = {
'project':Project.objects.all()
}
return render(request, 'projects/projects.html', context = project)
settings.py configuration (app is installed)
STATIC_URL = 'static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
When I inspect the image element in the webpage, the source shows up as
src=""
None of the other calls to the model are appearing either.
Any help would be appreciated.
i think you forgot to add a for-loop in your template. try this:
{% for p in project %}
{{ p.title %}}
{% endfor %}
Make sure that the image field of your record in the database is full.
Access the required model with the python manage.py shell command and check if this model has a value of variable.image.url.

How to use greater than operator in django template

I am having an issue while implementing greater than operator in my template. I have a post in homepage which users can like and I have my friends' profile images displayed beside like count who like the post. Now if 10 friends like my post, i want only five of my friends' profile images to be displayed, and there will be a "+" at the end of displayed images. The "+" signifies that there are more friends who like my post. I tried this but it doesn't work:
Model:
class Profile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,blank=True,null=True)
profile_pic = models.ImageField(upload_to='ProfilePicture/', default="ProfilePicture/user-img.png", blank=True)
friends = models.ManyToManyField('Profile', related_name="my_friends",blank=True)
class Post(models.Model):
poster_profile = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, blank=True,null=True)
likes = models.ManyToManyField('Profile', related_name='image_likes', blank=True)
View:
def home(request):
#all post in homepage
posts = Post.objects.filter(poster_profile=request.user)
#Show friend who liked Post
friends_like_img = request.user.profile.friends.all().order_by('-id')
context = {'posts':posts,'friends_img':friends_img}
return render(request, 'template.html', context)
Template:
{% for post in posts %}
{% for img in friends_img %}
{% if img in post.likes.all > 20 %}
<img src="{{ img.profile_pic.url }}" height="25" width="25" alt="profile_pic">
{% else %}
<img src="{{ img.profile_pic.url }}" height="25" width="25" alt="profile_pic"> +
{% endif %}
{% endfor %}
{% endfor %}
Your code is a bit of a mess, but here are some pointers:
You only ever want five images, so take care of that in the view by slicing the queryset:
friends_like_img = request.user.profile.friends.all().order_by('-id')[:5]
Your template syntax is all off, you could do with reading the docs and getting used to some examples. In the context, you're using friends_img, not friends_like_img - the context is what the template cares about. Now, since we only ever have five images, we can do this in the template:
{% for img in friends_img %}
<img src="{{ img.profile_pic.url }}" ...>
{% endfor %}
{% if post.likes.count > 5 %}
+
{% endif %}

Django - Display ImageField

I've just started to use Django and I haven't found a lot of info on how to display an imageField, so I made this:
models.py:
class Car(models.Model):
name = models.CharField(max_length=255)
price = models.DecimalField(max_digits=5, decimal_places=2)
photo = models.ImageField(upload_to='site_media')
views.py:
def image(request):
carx = Car()
variables = RequestContext(request,{
'carx':carx
})
return render_to_response('image.html',variables)
image.html:
{% extends "base.html" %}
{% block content %}
<img src=carx />
{% endblock %}
I already save an image since terminal and I know is there, also if a do this in image.html:
{% block content %}
{{ carx }}
{% endblock %}
The output is: Car object
Can anyone tell me where is my error?
An ImageField contains a url attribute, which you can use in your templates to render the proper HTML.
{% block content %}
<img src="{{ carx.photo.url }}">
{% endblock %}
You can also make use of the Static URL in Settings.py. Make a directory for example "Uploads", in the Static directory of your app. Also change this in your model in models.py.
Use the following code:
<img src="{% static carx.photo.url %}" />
Thanks to all, i fix it in this way.
views.py
def image(request):
carx = Car.objects.all()
for mycar in carx:
MyCar = mycar.photo.url
variables = RequestContext(request,{
'carx':MyCar
})
return render_to_response('image.html',variables)
image.html
{% extends "base.html" %}
{% block content %}
<img src="{{ MEDIA_URL }}{{ carx }}"/>
{% endblock %}
settings.py
MEDIA_URL = '/Users/gcarranza/PycharmProjects/django_bookmarks/'
STATIC_URL = '/Users/gcarranza/PycharmProjects/django_bookmarks/site_media/'
STATICFILES_DIRS = (
'/Users/gcarranza/PycharmProjects/django_bookmarks/site_media',)
Now i know that carx.photo.url retrieve the absolute path of the file and its only matter to load as static file.

Django - Loading a full image on separate page

I've been trying to put a hyperlink on my image thumbnail which would take the user to a full size image. but I keep on getting an error.
here as it shows, scribblemedia is a ForeignKey to scribble
models.py
class ScribbleMedia(models.Model):
media = models.FileField(upload_to=get_file_path)
def __unicode__(self):
return self.media
def find_typecheck(self):
filename = self.media.name
try:
ext = filename.split('.')[-1]
imgcheck=['jpg','jpeg','png','gif','tiff','bmp']
if ext in imgcheck :
chk='image'
else:
chk='other'
except Exception:
chk='not supported'
return chk
class Scribble(models.Model):
title = models.CharField(max_length=120)
body = models.TextField()
user = models.ForeignKey(User)
media = models.ForeignKey(ScribbleMedia)
def __unicode__(self):
return u'%s, %s' % (self.user.username, self.media)
views.py
#login_required
def image_page(request,pk):
img=get_object_or_404(ScribbleMedia,pk=pk)
image=img.media
variables= RequestContext(request,{
'image': image
})
return render_to_response('image_page.html',variables)
urls.py
(r"^image/(\d+)/$", image_page),
image_page.html
{% if image %}
<img src= {{ image.url }} />
This is the page where the image thumbnail is available
scribble_page.html
{% if scribble.media.media %}
{% if scribble.media.find_typecheck == 'image' %}
{% thumbnail scribble.media.media.url "700x500" crop="center" as im %}
<img src="{{ im.url }}" width="{{ im.width }}" height="{{ im.height }}">
{% endthumbnail %}
{% else %}
do something else
{% endif %}
{% endif %}
It keeps on giving me the following error:
TemplateSyntaxError at /image/2/
Unclosed tag 'if'. Looking for one of: elif, else, endif
The if statements in your scribble_page.html are fine. You need to close your if block in your image_page.html template...
{% if image %}
<img src="{{ image.url }}" /> <!-- Also note the added quotations... -->
{% endif %} <!-- This is the line you need to add -->

Categories

Resources