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.
Related
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.
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 %}
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 %}
I have a Photo model with two fields:
title = models.CharField()
path = models.CharField()
When I adding the new photo in admin panel, the path is equals to /images/image_ex.jpg This is my view file:
def gallery(request):
photos = Photo.objects.all()
return render(request, 'gallery.html', {'photos': photos})
This is the tag in gallery.html:
{% loadstaticfiles %}
<img src="{%static '{{photo.path}}'%}"/>
The problem is that the photo does not render and if I look in the code of the page, the src is equals to something like that:
src="static/%7B%7B%20photo.path%20%7D%7D"
What is the problem? How can I use template variables in src?
P.S. The images folder exists in static folder, the image exists too. I added static directory to settings.py. Also if I change src to a normal one, like
<img src="{static 'images/image_ex.png'%}">
The photo renders normally.
You here pass '{{photo.path}}' as a string to {% static ... %}, hence it will simply prepend the static URL root to this string.
If you want to use the content of photo.path, you can use:
<img src="{% static photo.path %}"/>
So {% static ... %} accepts variables as parameters, and will take the content of the path attribute of the photo variable. (of course given that variable is passed, or is a variable you generate with {% for ... %} loops, etc.
Uses a for tag
{% for p in photos %}
<img src="{% static '{{ p.path }}' %}"/>
{% endfor %}
Better uses Imagefield as field in your model
In your settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
Create a folder named “media” in your project (at the same level that your apps)
In your urls.py (main)
from . import views, settings
from django.contrib.staticfiles.urls import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
In your models.py
Replace the CharField with Imagefield
image = models.ImageField(upload_to="my_folder_name")
Like this:
class Photo(models.Model):
title = models.CharField()
image = models.ImageField(upload_to="my_folder_name"))
In your views.py
def gallery(request):
photos = Photo.objects.all()
return render(request, 'gallery.html', {'photos': photos})
In your templates
{% for p in photos %}
<img src="{{ p.photo.url }}"/>
{% endfor %}
Do it like this:
<img src="{static 'images/'%}{{image_ex.png}}">
Use it after the static tag scope ends.
For Template
{% for image in all_image %}
<img src="{{ image.image.url }}"/>
{% endfor %}
Solved: load image dynamically in survey.html
"survey.toolsTechnology" is a dynamic variable, every time the
variable changes, the image also changes based on it.
<img src="{% static 'images/'%}{{survey.toolsTechnology}}.png"/>
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 -->