Django 1.6 image upload and media path - python

So I have a project on webfaction where I need to create two different environments, one to server django and one to server static files.
So when I upload an image from admin panel I can see the image is placed in root i defined but with full path. When i return the image in my view i get my domain.com/full/media/root/path/imagename
this generates a broken link - when i go to mydomain.com/uploads/image_name, I can see image file is there however my link is pointing to full path rather than root_url,
Could you please help me with this? I really dont understand how i can correct this image link in my view
<img src="{{ MEDIA_URL }}{{ mymodel.my_image }}" alt="{{ name }}" width="150" height="200" />
I do understand there are so many subjects similar to this here however none of them could direct me correctly in regards to how to hide or change path root to "uploads"
I have which works fine in my admin
class Movie(models.Model):
name = models.CharField(max_length=50)
def get_file_path(instance, filename):
ext = filename.split('.')[-1]
filename = "%s.%s" % (uuid.uuid4(), ext)
return os.path.join( '/home/user/webapps/project/uploads/' , filename)
my_image = models.ImageField(upload_to = get_file_path, null=True, blank=True)
def __unicode__(self):
return self.name
In my settings:
MEDIA_ROOT = '/home/user/webapps/project/uploads/'
MEDIA_URL = '/uploads/'
and project url:
from django.conf.urls import patterns, include, url
from django.conf import settings
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
)
if settings.DEBUG:
urlpatterns += patterns('',
(r'^uploads/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT}))
Thank you all in advance

At first for your model you should create an image field and in there you should define where you want to upload your image:
class mymodel(models.Model):
name = models.CharField(max_length=50)
my_image = models.ImageField(blank=True, null=True,upload_to='/home/user/webapps/project/uploads/')
After that in your template when you want to show your image after getting your model object from your database try this:
<img src="{{ mymodel.my_image.url }}" alt="{{ mymodel.name }}" width="150" height="200" />

You can use:
{{ mymodel.my_image.url }}

Related

The 'cover' attribute has no file associated with it. Django

I want to display person pictures in a table with their name and surname columns. When i put as source static it show pictures but when i send request to database it didn't show. And its already insert data to database and picture to /media/images/.
view.py:
def viewpost(request):
person_list = Persona.objects.all()
if request.method == 'POST':
if request.POST.get('name') and request.POST.get('surname') and request.POST.get('address'):
person = Persona()
person.name = request.POST.get('name')
person.surname = request.POST.get('surname')
person.address = request.POST.get('address')
person.age = request.POST.get('age')
person.cover = request.FILES['cover']
person.save()
return HttpResponseRedirect('/viewpost')
else:
return render(request, 'mysite/viewpost.html', {'persons': person_list})
model.py:
class Persona(models.Model):
name = models.CharField(max_length=255, unique=False)
surname = models.CharField(max_length=255, unique=False)
address = models.TextField()
age = models.CharField(max_length=255, unique=False)
cover = models.ImageField(upload_to='images/')
and template:
<td ><img src="{{person.cover.url}}" class="img-responsive" width="40px" id="pop" data-toggle="modal" data-target="#myModal"/></td>
Without having settings and template code it´s difficult to get the whole picture, but here you have some tips:
To show static files in a template remember to use the {% load static %} tag.
Anyway, user uploaded files live better in a media folder, not in static. You should include it in your settings.py
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
If problem is not solve. Try this.
in urls.py add this in bottom:
from django.conf.urls.static import static
from django.conf import settings
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
in html template
<form method="post" enctype="multipart/form-data">
in settings.py
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, "media")

I can upload images to specific directory but can't view them in template (Page not found (404))

I am trying to add upload image to admin form in my Django project I found on GitHub. I can upload image to folder my_app(catalog)/media/images/image.png but when I try to call it in the template I can only see that image icon that appears when there is no picture.
settings.py
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'catalog/media')
model.py
class Book(models.Model):
image = models.ImageField(blank=True, null = True, upload_to='images')
book_detail.html
img src="{{ book.image.url}}" width="250"
views.py
class BookDetailView(generic.DetailView):
model = Book
urls.py
from django.urls import path
from . import views
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
path('', views.index, name='index'),
path('book/create/', views.BookCreate.as_view(), name='book_create'),
path('books/', views.BookListView.as_view(), name='books'),
path('book/<int:pk>', views.BookDetailView.as_view(), name='book-detail'),
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
This is how it looks like (I print {{ book.image }} next to the picture (images/screenshot_4.png):
This is the error I get:
You may have dropped a ']' at the end of your urlpatterns or maybe I am mistaken
Ok I found out after spending way to much time on it.
img src="{{ book.image.url}}" width="250" line in template should look like
img src="../media/{{ book.image.url}}" width="250".
Hope this helps someone with the same problem.

Display images form the admin panel

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 %}

django image upload to path is not displaying

I have an application where I upload images and the images are uploaded to a specific directory but after uploading which works fine if I attenp to click on the image url I get an error which says
The current URL, media/gallery/2017/12/28/230-256.png, didn't match any of these and also the image is not displaying in the browser html
below is my model and view despite having my media path defined in the settings
Models.py
class Gallery(models.Model):
name = models.CharField(max_length=400, db_index=True)
image = models.ImageField(upload_to='gallery/%Y/%m/%d', blank=True)
class Meta:
ordering = ('name',)
def __str__(self):
return self.image.url
Views.py
def index(request):
gallery = Gallery.objects.all()
context = {
'gallery': gallery,
}
template = 'gallery.html'
return render(request, template, context)
html
{% if gallery.image %}
<div><img src="{{ gallery.image.url }}"></div>
{% endif %}
While you are developing, in the project urls.py you must add
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
This will make your uploaded file accessible by the application.
When on a production server, it is better if the webserver itself (apache, nginx, ..) can reach the location where the files are uploaded, you can find how to configure that in other answers (here for nginx, and here for apache
Your HTML needs to be something like this:
{% if gallery.image %}
<div><img src="{{ MEDIA_URL }}{{ gallery.image.url }}"></div>
{% endif %}
MEDIA_URL should be configured in settings.py. This should be set to the base URL from where you're serving the files stored in MEDIA_ROOT.
The URL attribute of the image field stores only the relative URL of the image.

how to access upload images

I am creating one app using following two url's , homepage.html and detail.html.
*models.py*
class News(models.Model):
primary_image = models.ImageField("Main Image ",upload_to = "static/uploadedImg/main",)
secondary_Image = models.ImageField("Sub Image",upload_to = "static/uploadedImg/sub",)
In settings.py I had defined MEDIA and MEDIA_ROOT
I want to display random primary_image in homepage.html with primary_image as a link.
*articles.html*
<div id = "randommainImage">
<img src = "{{random_object.primary_image}}">
</div>
NewArticles
articles
db.sqlite3
manage.py
media
NewsArticles
README.md
static
NewsArticles\articles
admin.py
forms.py
models.py
static
Templates
tests.py
urls.py
views.py
Also, I want to display both primary_image & secondary_Image in a detail.html
Can anybody help me?
If you've defined correctly MEDIA and MEDIA_ROOT, to display the first image in the article.html template you use:
<img src = "{{ MEDIA_ROOT }}{{ random_object.primary_image }}" />
and likewise in the detail.html template:
<img src = "{{ MEDIA_ROOT }}{{ random_object.primary_image }}" />
<img src = "{{ MEDIA_ROOT }}{{ random_object.secondary_image }}" />
If you have these in your settings properly then you're ready to go:
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "media")
MEDIA_URL = '/media/'
A folder called media will be created to upload all the images in that folder.
Your image fields should look like this, I don't get why are you creating a folder for them in the static folder..
primary_image = models.ImageField(upload_to='uploadedImg/main/')
secondary_image = models.ImageField(upload_to='uploadedImg/sub/')
So your primary image will be in media/uploadedImg/main/img.png
View can look like:
def index(request):
context_dict = {}
news = News.objects.all()
context_dict['news '] = news
return render(request, 'index.html', context_dict, )
And to get the primary image you'll use {{ news.primary_image.url }} in your template.
edit>
Add this in your urls.py
from django.conf import settings
# ... your normal urlpatterns here
if settings.DEBUG:
# static files (images, css, javascript, etc.)
urlpatterns += patterns('',
(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT}))

Categories

Resources