Image Not displaying in django getting 404 error

ⅰ亾dé卋堺 提交于 2019-12-12 05:07:24

问题


I followed official django documentation for image field.I am able to store the image in the database but when I try to display it in browser I am getting 404 error.

My settings file,

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR,"templates")],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'django.template.context_processors.media',
                'django.core.context_processors.static',
            ],
        },
    },
]

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_URL = '/static/'
STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static")]
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR),"static")
MEDIA_ROOT =  os.path.join(os.path.dirname(BASE_DIR),"media")
MEDIA_URL = '/media/'

My models.py file,

class Add_prod(models.Model):
    book = models.CharField("Book Name",max_length=40)
    image = models.ImageField(upload_to='static/images',null=True)

My views.py file,

def add_prod(request):
    form = ProdForm(request.POST or None,request.FILES or None)
    my_products = Add_prod.objects.all()
    context = {
            "form":form,
            "products":my_products
    }
    if form.is_valid():
        instance = form.save(commit=False)
        book = form.cleaned_data.get("book")
        image = form.cleaned_data.get("image")
        instance.book = book
        instance.image = image
        instance.save()
   return render(request,"add-prod.html",context)

Small part of my urls.py file,

from django.conf import settings
from django.conf.urls.static import static

if settings.DEBUG:
    urlpatterns += static(settings.STATIC_URL,document_root=settings.STATIC_URL)
    urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_URL)

Small part of my template file,

{% for i in products %}  
            <tr>
                <td>{{i.book}}</td>
                <td><img src="{{ MEDIA_URL }}{{i.image.url}}" alt="No Image"></td>
            </tr>
{% endfor %}

This is the error in the eclipse console,

Not Found: /media//media/static/images/644.jpg
"GET /media//media/static/images/644.jpg HTTP/1.1" 404 1800

回答1:


In urls.py, I am noticing it has to be:

static(settings.STATIC_URL,document_root=settings.STATIC_ROOT) 

static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)



来源:https://stackoverflow.com/questions/37109582/image-not-displaying-in-django-getting-404-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!