【问题标题】:Can't get images to work in django无法让图像在 django 中工作
【发布时间】:2018-02-03 12:53:03
【问题描述】:

尝试在本地提供用户上传的文件时出现 404 错误。我已经尝试了很多来自论坛的建议,但我无法让它发挥作用。 这是我可以在日志中看到的错误。图像被正确上传到媒体/图像,但是当我尝试使用同一张图像时,我得到一个 404 未找到。我试图放置绝对路径,但也没有用。有人可以帮我吗?谢谢

[03/Feb/2018 23:32:00] "GET /idealistos/30/ HTTP/1.1" 200 483
Not Found: /media/images/_D3L8637.jpg
[03/Feb/2018 23:32:01] "GET /media/images/_D3L8637.jpg HTTP/1.1" 404 2239

settings.py

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static')

STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
# Media files
MEDIA_ROOT = 'media/'
MEDIA_URL = '/media/'

models.py

from django.db import models
from django.forms import ModelForm
from django.utils import timezone
from django.contrib.admin.widgets import AdminDateWidget

# Create your models here.
class Anuncio(models.Model):
    title = models.CharField(max_length=40)
    description = models.CharField(max_length=300)
    price = models.CharField(max_length=10)
    city = models.CharField(max_length=20)
    state = models.CharField(max_length=20)
    country = models.CharField(max_length=20)
    postcode = models.CharField(max_length=20)
    foto = models.FileField(null=True, blank=True, upload_to='images/')
    pub_date = models.DateTimeField(default=timezone.datetime.now())


def __str__(self):
    return self.title
def __unicode__(self):
    return price


class AnuncioForm(ModelForm):

class Meta:
    model = Anuncio

    fields = ['title', 'description', 'price', 'city', 'state', 'country','postcode','foto']

views.py

from django.http import Http404, HttpResponseRedirect
from django.views.generic import ListView
from django import forms
from django.utils import timezone
#from django.template import loader
from django.shortcuts import render, get_object_or_404, redirect
from .models import Anuncio, AnuncioForm

#Creates a list from a model. Used for the ad index view.
class AnuncioList(ListView):

model = Anuncio

#Creates a detail view of the Ad
def detail(request, anuncio_id):
try:
    anuncio_detalle = get_object_or_404(Anuncio, pk=anuncio_id)
    #anuncio_detalle = Anuncio.objects.get(pk=anuncio_id)
except Anuncio.DoesNotExist:
    raise Http404("Question does not exist")
return render(request, 'idealistos/detail.html', {'anuncio_detalle':anuncio_detalle})


def add_form(request):

if request.method == 'POST':
    form = AnuncioForm(request.POST,request.FILES)

    if form.is_valid():
        new_add = form.save()
        new_add.pub_date = timezone.now()



        return redirect ('idealistos:index')

else:
    form = AnuncioForm()

return render(request, 'idealistos/create_add.html', {'form':form,})

url.py

from django.conf.urls.static import static
from django.conf import settings
from django.urls import path
from . import views
from idealistos.views import AnuncioList

app_name ='idealistos'
urlpatterns = [
# ex: /idealistos/
path('', AnuncioList.as_view(), name='index'),
# ex: /idealistos/5/
path('<int:anuncio_id>/', views.detail, name='detail'),
#ex: /idealistos/add_form
path('add_form/', views.add_form, name='add_form'),

]
         urlpatterns+=static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)

模板

<head>
<link rel="stylesheet"    href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">
</head>

<body>


{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'idealistos/idealistos.css' %}" />


<h1>{{ anuncio_detalle }}</h1>
<ul>
<li>{{ anuncio_detalle.description }}</li>
<li>{{ anuncio_detalle.city }}, {{ anuncio_detalle.country }} CP:{{ anuncio_detalle.postcode }}</li>
<li>{{ anuncio_detalle.pub_date }}</li>
<img src={{anuncio_detalle.foto.url}}>
</ul>

</body>

【问题讨论】:

  • 我怀疑拥有 MEDIA_ROOT 的相对路径是否有意义。像对 STATIC_ROOT 所做的那样,使其成为绝对文件路径。
  • 我已经换成了这个,现在图片没有上传 MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'media') MEDIA_URL = '/media/'模型中 foto 的路径是 foto = models.FileField(null=True, blank=True, upload_to='images/')

标签: django python-3.x


【解决方案1】:

尝试提供MEDIA_ROOT 并在DEBUG=True 时提供urls.py

models.py

foto = models.ImageField(upload_to='images/', null=True, blank=True)

settings.py

MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'media')
MEDIA_URL = '/media/'

urls.py

from django.conf.urls import url, include
from django.contrib import admin
from django.views.static import serve
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
   #Other Urls
   . . . . .
   . . . . . 

   # admin
   url(r'^admin/', admin.site.urls),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

if settings.DEBUG:
    urlpatterns += [
        url(r'^media/(?P<path>.*)$', serve, {
            'document_root': settings.MEDIA_ROOT
        }),
    ]

【讨论】:

  • 感谢您的回答。还是行不通。如果我使用 MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'media') 图像不会被写入 media/images/。我的表单具有以下内容: foto = models.FileField(null=True, blank=True, upload_to='images/') 我应该更改该属性吗?
  • 谢谢。正如你所说,我使用了 ImageField(必须安装 Pillow)并更改了 models.py、settings.py 和 url.py。现在图像正在正确上传到 ~/django/media/images 但图像的路径不正确:未找到:/idealistos/44/images/_D3L8458_lF9Nac1.jpg [04/Feb/2018 01:37:31] “GET /idealistos/44/images/_D3L8458_lF9Nac1.jpg HTTP/1.1" 404 3101
  • 当前路径,idealistos/46/images/23658378_1145199562278028_3235145770201548382_n.jpg,与这些都不匹配。
  • 找不到页面 (404) 请求方法:GET 请求 URL:localhost:8000/idealistos/46/images/…
  • 不知道为什么这个46来了??
【解决方案2】:

希望您正确查看上传的文件。

对于本地开发,请尝试在基本 urls.py 中添加以下内容

if settings.DEBUG is True:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

【讨论】:

  • 嗨,是的,我可以看到上传到 /media/images 的图像。但是现在看到这个错误。 Page not found (404) Request Method: GET Request URL: http://localhost:8000/idealistos/46/images/23658378_1145199562278028_3235145770201548382_n.jpg Django tried these URL patterns, in this order: ^arduinogui/ ^idealistos/ [name='index'] ^idealistos/ &lt;int:anuncio_id&gt;/ [name='detail'] ^idealistos/ add_form/ [name='add_form'] ^idealistos/ ^media\/(?P&lt;path&gt;.*)$ ^idealistos/ ^media\/(?P&lt;path&gt;.*)$
猜你喜欢
  • 1970-01-01
  • 2016-12-13
  • 1970-01-01
  • 2013-05-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-12
相关资源
最近更新 更多