0

Excuse me, but my Django doesn't display uploaded image. I think the codes worked before. Where should I change in my codes?

[19/Apr/2016 21:09:27] "GET /static/myapp/image/resize/yu_popup.jpg HTTP/1.1" 404 1729

And I read some web pages which said we must use MEDIA_ROOT only in development environment, so I don't use MEDIA_ROOT. Is this problem caused because I don't use MEDIA_ROOT and should I use MEDIA_ROOT even when I release my application?

$ tree
.
|-- db
|   |-- myapp.sqlite3
|-- db.sqlite3
|-- myapp
|   |-- __init__.py
|   |-- admin.py
|   |-- apps.py
|   |-- forms.py
|   |-- media
|   |   `-- resize
|   |       `-- photo.JPG
|   |-- migrations
|   |   |-- 0001_initial.py
|   |   |-- 0002_resize.py
|   |-- models.py
|   |-- static
|   |   `-- myapp
|   |       |-- image
|   |       |   `-- resize
|   |       |       |-- yu_popup.jpg
|   |       `-- js
|   |-- templates
|   |   |-- base.html
|   |   `-- myapp
|   |       |-- resize
|   |       |   `-- resize.html
|   |-- tests.py
|   |-- urls.py
|   `-- views.py
|-- manage.py
|-- myproject
|   |-- __init__.py
|   |-- __pycache__
|   |-- settings.py
|   |-- urls.py
|   `-- wsgi.py
`-- static
    `-- myapp
        `-- image
            |-- resize
            |   |-- 1454049232616.jpg
            `-- resize_wHx2hQC

settings.py

# -*- coding: utf-8 -*-
DEBUG = True
ALLOWED_HOSTS = []

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myapp',
    'debug_toolbar',
    'social.apps.django_app.default',
]

MIDDLEWARE_CLASSES = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    #'django.middleware.cache.UpdateCacheMiddleware',
    'django.middleware.common.CommonMiddleware',
    #'django.middleware.cache.FetchFromCacheMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'social.apps.django_app.middleware.SocialAuthExceptionMiddleware',
]

APP_DIR = os.path.join(BASE_DIR, 'myapp')
#STATIC_ROOT = os.path.join(APP_DIR, "staticroot")
STATIC_URL = '/static/'

STATICFILES_DIRS = (
    #os.path.join(BASE_DIR, 'static'),
    os.path.join(APP_DIR, 'static'),
)

STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
    #'django.contrib.staticfiles.finders.DefaultStorageFinder',
)

#MEDIA_ROOT = os.path.join(APP_DIR,"media")
#MEDIA_URL = '/media/'

views.py

def resize(request):

    #import pdb; pdb.set_trace()
    from myapp.forms import Resizef
    formset = Resizef
    photo = ""

    if request.method == 'POST':
        form = formset(request.POST)
        try:
            from myapp.models import Resize
            new_photo = Resize()
            new_photo.photo = request.FILES['photo']
            new_photo.save()
            photo = Resize.objects.get(id=new_photo.id)  # 
        except:
            pass
    else:
        form = formset()

    view = {'form': form, 'photo': photo}

    template = 'myapp/resize/resize.html'

    return render(request, template, view)

models.py

def resize_based_upload_to(instance, filename):
    return "static/myapp/image/resize/{}".format(filename)


@python_2_unicode_compatible  
class Resize(models.Model):
    photo = models.ImageField(upload_to=resize_based_upload_to)

    class Meta:
        db_table = traceback.extract_stack()[-2][2].lower()

resize.html

<html>
<body>
    <form action="" method="post" enctype="multipart/form-data">
    {% csrf_token %}
        {{ form.photo }}  <br />
        <button type="submit">
            <span>Upload</span>
        </button>  <br />
    </form>

    <h3>Upload Photo</h3>  <br />
    <img src="/{{ photo.photo }}" />  <br />
</body>
</html>

Python3.5, Django1.9

physicalattraction
  • 6,485
  • 10
  • 63
  • 122
yamachan
  • 1,029
  • 2
  • 12
  • 28
  • 2
    Does the requested file `/static/myapp/image/resize/yu_popup.jpg` exist? – John Gordon Apr 19 '16 at 14:55
  • @John Gordon Thank you for your reply. Yes, it exists. I upload a jpegfile to Resize model and it send the path to resize.html. I checked whether the image file exists or not. – yamachan Apr 19 '16 at 15:21
  • 1
    You read the advice wrongly... you still need to have `MEDIA_ROOT` setting defined. The common advice regarding media files and django dev vs live is related to _serving_ the files, i.e. don't use the `django.view.static.serve` view in your urls.py for live (your web server should serve them directly) see http://stackoverflow.com/a/5518073/202168 (in that example they use `settings.DEBUG` setting to distinguish the dev server from live) – Anentropic Apr 19 '16 at 15:23
  • @Anentropic Thank you for your advice. I got it. Following your advice, I will use MEDIA_ROOT and change my url.py. It is already midnight here, so I'll try later. Thanks. – yamachan Apr 19 '16 at 15:34
  • @Anentropic Following the link, I added codes, `if settings.DEBUG: urlpatterns += [ url(r'^media/(?P.*)$', 'django.views.static.serve', { 'document_root': settings.MEDIA_ROOT}), ]` in `urls.py` and `MEDIA_ROOT = os.path.join(APP_DIR,"media") MEDIA_URL = '/media/'` in `settings.py`. But this occurs again. `[20/Apr/2016 10:57:38] "GET /resize/cat.gif HTTP/1.1" 404 14590` What am I missing? – yamachan Apr 20 '16 at 02:02
  • I made sure `/myproject/myapp/media/resize/cat.gif` exists and Resize.photo is `resize/cat.gif`. – yamachan Apr 20 '16 at 02:08
  • I am sorry, I found what I was missing. I had to change `resize.html` to ``. – yamachan Apr 20 '16 at 02:29
  • 1
    you shouldn't hard-code the `MEDIA_URL` (`/media/`) in your template like that. you can get Django to give you the full url, see here http://stackoverflow.com/a/8850622/202168 – Anentropic Apr 20 '16 at 09:36
  • @Anentropic Thank you for your reply. Ah, sorry, I tried to modify the part, but I couldn't. I wrote ``. Is this way ok? Or still bad way? – yamachan Apr 20 '16 at 09:46
  • It's better, but you shouldn't need to do that. See the link above, you should be able to do `` – Anentropic Apr 20 '16 at 09:59
  • @Anentropic Thank you for your advice. It worked. I appreciate your kindness. Thank you so much. – yamachan Apr 20 '16 at 12:41

0 Answers0