I am trying to get django to show pictures. Ive installed PIL and it seams to work.
i am running py 2.7, win 7, the developement server and sqlite3
my static root:
STATIC_ROOT = r'H:/netz2/skateproject/static/'
ive got a background picture in this folder and can acces it via
http://127.0.0.1:8000/static/images/lomax.jpg
now im trying to upload a pic via an image field & the admin. it works fine, the picture lands in the right folder (ive changed the folders a million times by now to see if that could be the problem) but the picture can not be displayed.
part of my model:
class Sk8(models.Model):
name = models.CharField(max_length=50, default='name of the model')
bild1 = models.ImageField(upload_to="uploads/")
my media root:
MEDIA_ROOT = r'H:/netz2/skateproject/media/'
the picture lands in the right folder. netz/skateproject/media/pic.jpg
but it seams like localhost can not acces this folder. when i try - i get an 404 and django tells me that the url does not match anything i defined in my urls.
which is true - but neither did I define a url for the background image in the static folder - and i can access this one just fine.
ive also tried to acces the file from my html template, like this:
{% extends "grundgerüst.html" %}
{% block inhalt %}
<div id='skatelist'>
{% for sk8 in skates %}
<p>{{sk8}}</p>
<p><img src="{{sk8.bild.url}}"/></p>
{% endfor %}
</div>
{% endblock %}
obviously the picture does not show up.
I dont know what is wrong here. i guess i shoudl be able to see the pic on localhost?
heres a pic of the error chrome gives me
if i.e. in the picture the folders are different than the ones in the code example its because i changed them testing different settings.
I really hope somebody can help me to figure out image_field, cause uploading pictures if i cant display them does not make much sense :)
thanks in advance!!!
danielll
ouh and - i already tried google and django reference etc. i honestly could not figure it out that way. every help appreciated!
Django's contrib.staticfiles app will monkeypatch your urls to serve static files when in DEBUG mode [ref]. Unfortunately the same cannot be said of media files.
Add the following snippet to your project urls.py to display media
django.conf import settings
if settings.DEBUG:
urlpatterns += patterns('',
url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT,
}),
)
Docs reference
Related
I have some problems in django,
I can load images in my index.html, but not in other templates,
why is this happening?
Tried many methods and viewed many other post but non work for me.
This is my urls.py
urlpatterns = patterns('',
# Examples:
url(r'^$', 'userboard.views.home', name='home'),
url(r'^items/(?P<UserBoard_id>\d+)/$','userboard.views.details',name='details'),
url(r'^upload.html$', 'userboard.views.upload', name='upload'),
url(r'^items/(?P<UserBoard_id>\d+)/delete.html$','userboard.views.delete',name='delete'),
url(r'^items/(?P<UserBoard_id>\d+)/edit.html$','userboard.views.edit',name='edit'),
url(r'^media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT}),
This is my index.html, it works fine
<h1> Your Items: </h1>
<ul>
{% for items in ItemList %}
<li><a href="/items/{{items.id}}/">
<img src="{{items.itemImage}}"></a>
</li>
<hr />
{% endfor %}
</ul>
Add a new item
but this wont load my pictures
<img src="{{item.itemImage}}">
<h1>{{item.itemName}}<h1>
<h2>{{item.itemDesc}}</h2>
<br /><br/><br/>
Delete this item
<br />
Edit this item
i am not sure if you need my views, here they are
def home ( request) :
ItemList= models.UserBoard.objects.all()
return render_to_response('index.html',{'ItemList':ItemList})
def details(request,UserBoard_id):
try:
item=models.UserBoard.objects.get(pk=UserBoard_id)
except models.UserBoard.DoesNotExist:
raise Http404
return render_to_response('details.html' ,{'item':item})
Please let me know where I went wrong or at least give me a hint where I could start searching on.
EDIT:
here are my models
from django.db import models
class UserBoard(models.Model):
itemName=models.CharField(max_length=100)
itemDesc=models.CharField(max_length=400)
itemImage=models.ImageField(upload_to='../media/pictures')
if i print out the value of items.itemImage, it will show this ../media/pictures/d.jpg
Same value in both pages, but image will only show on 1. Templates for both pages are at the same folder.
And here is my settings.py media root
MEDIA_ROOT = '/home/rox/Documents/IP/userboard/media/'
MEDIA_URL = 'media/'
PROBLEM SOLVED
THANKS A LOT to little_birdie and the others out there who helped.
The problem was this . I didn't put the '/' infront of item.itemImage previously.
However, why is it that without the / it works in the index.html but not the others?
Not quite enough information but I think I know what's going on here.
You are getting a relative path from item.itemImage, that is.. it does not start with a slash, so the browser will load it relative to the url of the page the image is on.
Apparently you stored the full url path to your image in your image field, eg:
media/foo/myphoto.jpg
When loaded from / (home page) becomes '/media/foo/myphoto.jpg'.. which works.
The bottom line is, do this:
<img src="/{{item.itemImage}}">
When I try text editing and other text related stuffs and save it, the editor does its job nicely. But when I try to upload an image it just take a different url. I am on windows. Is it because of this, cause I saw a post on this post, but it didn't helped me either. It does get saved and they each have their own thumbnails too. But its just that the wrong urls.
I checked the src of the image, and it was like this,
<img alt="" src="/media/3/10/17Hydrangeas.jpg" />
But it should have been like this,
<img alt="" src="/media/2013/10/17/Hydrangeas.jpg" />
And sometimes the src of the image is just like this,
<img alt="" src="/media/3/10/17" />
This is the snippet of my settings.py:
CKEDITOR_UPLOAD_PATH = 'C:/Users/Nanyoo/web/demo/media'
MEDIA_ROOT = 'C:/Users/Nanyoo/web/demo/media'
I've included its url in my urls.py:
(r'^ckeditor/', include('ckeditor.urls')),
models.py:
from django.db import models
from datetime import datetime
from django.contrib.auth.models import User
from time import time
def get_upload_file_name(instance, filename):
return "uploaded_files/%s_%s" %(str(time()).replace('.','_'), filename)
class Blog(models.Model):
title = models.CharField(max_length=200)
image = models.ImageField(upload_to=get_upload_file_name, blank=True)
pub_date = models.DateTimeField(default=datetime.now)
creator = models.ForeignKey(User, related_name="creator_set")
body = models.TextField()
In the forms.py:
from django import forms
from django_summernote.widgets import SummernoteWidget
from ckeditor.widgets import CKEditorWidget
class BlogForm(forms.Form):
title = forms.CharField(max_length=200,widget=SummernoteWidget())
body = forms.CharField(widget=CKEditorWidget())
In the index.html:
{% for blog in blogs %}
<div id="page">
<h1>{{ blog.title | safe}}</h1>
<p>{{ blog.body | safe}}</p>
</div>
{% endfor %}
my form in the html:
{% block content %}
<form method="post" action=".">
{% csrf_token %}
<fieldset id="create_blog">
{{form.media}}
{{ form.as_p}}
<input type="submit" value="Post Blog" />
</fieldset>
</form>
{% endblock %}
I had a bit of a time getting django-ckeditor up and running with my Django app, but eventually hacked my way through to being able to serve uploaded files on the local machine (during development/testing).
First thing I suggest doing - if you haven't done so already - is read Django's documentation regarding static files. It may help in getting a better idea as to how things are configured and why.
From the django-ckeditor installation documentation, step 4 outlines the purpose of CKEDITOR_UPLOAD_PATH This works similarly to Django's built-in MEDIA_ROOT and STATIC_ROOT, where the path provided isn't necessarily the path in which the file is stored. You must specify a path to store the file upon upload. This may be done by making sure you have a MEDIA_URL global variable declared within your projects settings file.
Once you have the initial setup complete, the final step is to enable Django to serve the files you're working with locally. Please note: This method is to be used for development and debugging purposes only. Do not deploy your code with the following snippet included.
You may read more on this method via Django's static file how-to, within the "Serving static files during development" section.
In your project's urls.py file, add the following bit of code, enabling Django to serve your local data.
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = patterns(
'',
# existing url patterns,
# ...,
) + static(settings.MEDIA_URL, document_root=settings.STATIC_ROOT)
From there, you should be all set.
Just as a quick disclaimer: I am by far a seasoned professional. This method is what has worked for me, given my specific setup and environment. Results may vary.
Hope this helps to get you headed in the right direction. Best of luck!
CKEDITOR_UPLOAD_PATH is relative to MEDIA_ROOT.
https://github.com/django-ckeditor/django-ckeditor#id2
In your case it should be
CKEDITOR_UPLOAD_PATH = ''
This worked for me. To be honest, all these *_PATH issues were probably the hardest parts of Django for me.
UPD: I see that probably your issue was of some other sort. However I noticed the error in your configuration, that's why I wanted to fix that, since I had troubles with that and other people may find this issue and my answer too. Maybe your configuration was even right, if they've changed the defaults since the time of your post.
I made it !!!
Problem solved !!!!!!
I have the same problem just as you.
Did you solve that?
Did you change
CKEDITOR_UPLOAD_PATH = 'uploads/'
to something else?? Don't change if wrong.
Every time after I successfully upload the picture to the server using django-ckeditor, the django-ckeditor would request a URL which looks like this
uploads/2015/06/11/app_software_360.jpg
And that indicates the browser is requesting to
localhost:8000/somewhere/someplace/uploads/2015/06/11/app_software_360.jpg
but not localhost:8000/media/uploads/2015/06/11/app_software_360.jpg This is the actually right URL location, but django-ckeditor just can not find it out. I guess this has something to do with the settings.py
You can check out this page github issue
By adding these to settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
MEDIA_URL = '/media/'
It works!
Thumb up if you think this is helpful. :)
I have a model with this field:
image=models.ImageField(upload_to='company-category')
company-category is a folder in uploads folder,but I want to upload images to template directory .I think this way users that visit my website can't access images and download them.
in settings:
TEMPLATE_DIRS = (
"C:/ghoghnous/HubHub/Theme"
)
how can I do this?
Here I'm giving two solutions. The one you asked and then my suggestion.
Use the following code to set the upload location to your templates folder.
from django.conf import settings
image=models.ImageField(upload_to = settings.TEMPLATE_DIRS[0])
The above code will upload image to your template directory.
My Suggestion:
Upload images to your media folder. Then use the MEDIA_URL to allow users to download them. Use the following code to define them.
settings.py
MEDIA_ROOT = 'C:/ghoghnous/HubHub/media'
MEDIA_URL = 'site_media'
urls.py
from django.conf import settings
urlpatterns += patterns('',
url(r'^site_media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}),
)
models.py
class SampleModel(models.Model):
image = models.ImageField(upload_to = 'images')
If you use this, the images will be uploaded to the folder C:/ghoghnous/HubHub/media/images/. Then get your required images by using objects.get or objects.filter.
record = SampleModel.objects.get(id = 1)
If I print record.image, the output will be images/filename.jpg.
Pass this to your template. Then you can display the image or give download link as follows:
<a href="{{ record.image.url }}/" >Download</a> #Download link
<img src="{{ record.image.url }}/" /> #To display image
<a href="/site_media/images/file.jpg" >Download</a> #Download static files
I suggest you using the second method, since saving images in templates folder is not adviced.
Template directory is not a preferred place to store media as per Django good practices.
Also, any images that you display on the web page will have a path and can be downloaded. Some people use scripting to stop right clicks and stuff like this but as far as I understand source code always give you image paths.
Oh, I think you'd like to upload the file to a temporary folder and then do something with it. Right?
You need to override method clean_image in forms. Then you can write your own code with any path you want using File storage
I've installed django-photologue and added a handful of photos to the database. The basic site mechanics seem to be working fine, except no photos or thumbnails are displayed. The images and thumbnails are in ..\django\media\photologue\photos.
For a photo_detail page, the resulting HTML source looks like this:
<title>Greece 3</title>
<h1>Greece 3</h1>
<div class="gallery-photo">
<img src="photologue/photos/cache/greece003_display.jpg" alt="Greece 3"/>
<p>no caption yet</p>
</div>
<h2>This photo is found in the following galleries:</h2>
<ol>
<li>
<a title="Greece 2" href="/photologue/photo/greece-2/"><img src="photologue/photos/cache/greece002_thumbnail.jpg"/></a>
LSB Photos - Greece
<a title="Greece 4" href="/photologue/photo/greece-4/"><img src="photologue/photos/cache/greece004_thumbnail.jpg"/></a>
</li>
</ol>
Looks to me like the img src files don't resolve to the right location and therefore don't display. I think MEDIA_ROOT and MEDIA_SITE are correct, and media for other apps work like i expect.
>>> import settings
>>> settings.MEDIA_ROOT
'c:/design.ed/django/media/'
>>> settings.MEDIA_URL
''
And here's what the photologue module itself gives me.
>>> from photologue import models as phl
>>> phl.PHOTOLOGUE_DIR
'photologue'
>>> phl.PHOTOLOGUE_PATH
>>> phl.get_storage_path(None, 'foo.jpg')
'photologue\\photos\\foo.jpg'
What am i missing here?
I think i've answered my own question. The problem had nothing whatsoever to do with photologue: rather, settings.MEDIA_URL wasn't set correctly (because i'd never actually served any media through Django before).
In my case, i was running locally using the default Django server (which i know you're not supposed to do for production). So i had this in my urls.py:
(r'^site_media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': MEDIA_ROOT, 'show_indexes': True}),
but MEDIA_URL was the default empty string. Instead i changed it to
MEDIA_URL = '/site_media/'
which is where it's supposed to be (both the leading and trailing slashes are required in this case), and all the magic worked. Apologies for clouding the issue with photologue details.
I have implemented photo upload in Django but I have a problem to view it Django admin.
models.py
class WorkPlacePhoto(models.Model):
file = models.FileField(storage=FileSystemStorage(location=settings.MEDIA_ROOT), upload_to='uploads')
Photos are saved in PATH_TO_APP/media/uploads/ and I can view them in my app. However, in admin panel, when I clicked on the link which admin app is generated it gives me 404 error as
Request Method: GET
Request URL: http://127.0.0.1/admin/wpphotos/workplacephoto/9/media/uploads/aosa_glb_ho_778_hi.jpg/
u'9/media/uploads/aosa_glb_ho_778_hi.jpg' object is not found
Although the message is clear, I couldn't figure out which url should be written to view the image and of course how admin class should be modified.
I glad to suggest me a way to achieve this. Thanks...
From you description I am guessing your MEDIA_URL isn't set correctly, something which is a bit tricky to do using the Django development web server.
I am guessing that the link's href would probably be media/uploads/aosa_glb_ho_778_hi.jpg where you probably want /media/uploads/aosa_glb_ho_778_hi.jpg so it is relative to http://127.0.0.1/ not to where you happen to be now http://127.0.0.1/admin/wpphotos/workplacephoto/9/.
See the static files documentation for inspiration of how to serve your images with the Django development server.
I have the same issue but I managed to fix it -but it's not a correct method and I'd like to use a better solution if possible.
What I did was, I have apache running on port 80, so I created a symbolic link in the /var/www folder which is pointing to the Images folder in my Django App directory. And the Media URL is basically this:
MEDIA_URL = 'http://127.0.0.1/Images/'
This work fine, but I don't like the solution.
I didn't quite follow the solution explained above. Could someone please explain more?
By now, you probably either solved your problem or quit it altogether, but after all these years people (like me) still have this problem. Here's how I just solved it:
On settings.py, I set not only STATIC_URL (with the name of the static folder) and STATIC_URL (with the path to that folder) but I also set MEDIA_URL and MEDIA_ROOT accordingly, where the uploaded images will be stored at;
On my model class, I have my picture field looking as follow:
picture = models.FileField(upload_to='images/')
It will upload the image to my MEDIA_ROOT folder, appending /images/ to it.
And finally, on my urls.py, my urlpatterns looks like this:
urlpatterns = [
url(r'^admin/', admin.site.urls),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Notice how I appended the static right after the list.
Django's documentation makes it clear that this strategy is not recommended for production environment and it gives some alternatives you can choose from. For more information: https://docs.djangoproject.com/en/1.10/howto/static-files/#serving-files-uploaded-by-a-user-during-development
You probably have in your settings.py
MEDIA_URL = 'media/'
Being the url relative, you have that behavior in the admin panel. The solution would be to set the url as absolute
MEDIA_URL = '/media/'