我正在使用Django构建一个网站,我试图让用户上传要使用的图像,这是我的文件:
settings.py
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home2/media/media.lawrence.com/media/"
MEDIA_ROOT = os.path.join(BASE_DIR, 'static/media')
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = '/media/'
models.py
class test1(models.Model):
dress_name = models.CharField(max_length=250, default='dress')
dress_size = models.CharField(max_length=50, default='5')
docfile = models.FileField(upload_to='documents/%Y/%m/%d',default ='upload')
views.py
def home(request):
all_dress = test1.objects.all()
context = {
'all_dress': all_dress,
}
return render(request, 'fostania/home.html', context)
以下是我在模板中使用它的方式
HTML
{% for item in all_dress %}
<div class="card" style="width: 18rem;">
<img class="card-img-top" src="{{ item.docfile.url }}" alt="Card image cap">
<div class="card-body">
<h5 class="card-title">{{ item.dress_name }}</h5>
<p class="card-text">{{ item.dress_size }}</p>
<a href="#" class="btn btn-primary">Go somewhere</a>
</div>
</div>
{% endfor %}
URLS.py
from django.contrib import admin
from django.template.context_processors import static
from django.urls import path
from django.contrib.auth import views as auth_views
from dress import settings
from fostania import views
urlpatterns = [
path('admin/', admin.site.urls),
path('login/', auth_views.login, name='login'),
path('home/',views.home, name='home'),
path('add/',views.add, name="add"),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
最后,图片永远不会显示..链接中始终是错误!!
请注意,图片在上传后会在静态/媒体文件中显示,所以我认为这是某种URL错误!
错误
错误是图像总是显示断开的链接,当我打开链接(打开图像链接)时,它会给我这个错误
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/media/documents/2018/05/18/test_dress3.jpg
答案 0 :(得分:1)
答案 1 :(得分:0)
<强>解决强>
这是一个错误的导入参考,我使用from django.conf.urls.static import static
而不是from django.template.context_processors import static
并且它有效。