无法让图像在django中工作

时间:2018-02-03 12:53:04

标签: django python-3.x

尝试在本地提供用户上传的文件时出现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>

2 个答案:

答案 0 :(得分:0)

UITableView时尝试提供MEDIA_ROOT并在urls.py投放。

<强> models.py

DEBUG=True

<强> settings.py

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

<强> urls.py

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

答案 1 :(得分:0)

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

对于本地开发,请尝试在您的基础urls.py

中添加以下内容
if settings.DEBUG is True:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)