有很多关于如何上传媒体文件的答案,正确的配置是什么以及如何在我们的应用程序中提供它。
但我的项目似乎什么都没做。
目标很简单:用户上传图片。 Django显示它。
models.py
class UploadImageModel(models.Model):
image = models.FileField()
title = models.CharField(max_length=100, null=True, blank=True)
urls.py
from django.conf.urls import url, include
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'', include("Image.urls")),
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
views.py
from django.shortcuts import render
from django.views import View
from .forms import UploadImageModelForm
from .models import UploadImageModel
# Create your views here.
class UploadImage(View):
def get(self, request, *args, **kwargs):
form = UploadImageModelForm()
context = {
"form":form,
}
return render(request, "index.html", context)
def post(self, request, *args, **kwargs):
form = UploadImageModelForm(request.POST or None, request.FILES or None)
if form.is_valid():
instance = form.save(commit=False)
instance.title = str(instance.image)
instance.save()
context = {
"form":form,
"instance":instance,
}
return render(request, "index.html", context)
settings.py
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, "Static")
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, "Media")
的index.html
{% if instance.image %}
<img src="{{instance.image.url}}" alt="Image"/>
{% endif %}
错误:上传名为<something>.jpg
的图片后,如果我访问127.0.0.1:8000/media/1.jpeg
,则浏览器不显示图片,而是显示index.html
页面。
那么如何正确地提供这个媒体文件呢?
答案 0 :(得分:1)
这一行是每个网址的全能:
url(r'', include("Image.urls")),
如果没有看到Image/urls.py
的内容,我只能建议用执行索引视图的显式模式替换该行,例如:
url(r'^$', my_index_view),