我有一张带有ImageField()
的表单我已经设置了媒体网址和目录,例如在setting.py和url.py中,并且提交的内容一切正常,但现在每次都突然我尝试提交我的表单失败并在python终端中说:
[17 / Feb / 2018 14:40:08]" POST / form / HTTP / 1.1" 200 37885
未找到:/ media /
我没有修改setting.py或url.py(请参阅下面的代码):
setting.py
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, "static")]
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
url.py
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
model.py
class Model_A(models.Model):
name = models.CharField(max_length=200, verbose_name="Name (as in NRIC)")
def upload_photo_dir(self, filename):
path = 'hiring/employees/photo/{}'.format(filename)
return path
photo = models.ImageField(upload_to=upload_photo_dir)
view.py
def application_form_view(request):
form = Model_AForm(request.POST or None, request.FILES or None)
if form.is_valid():
inst = form.save(commit=False)
inst.save()
context = {'form': form}
return render(request, 'form.html', context=context)
HTML
<form method="POST" enctype="multipart/form-data" id="application_form" name="application_form">
<label>name :</label>
{{ form.name}}
<label>Photo:</label>
{{ form.photo }}
</form>
答案 0 :(得分:0)
在Settings.py
中更改以下常量BASE_DIR = os.path.dirname(os.path.dirname(__file__))
MEDIA_ROOT = os.path.join(BASE_DIR, 'media').replace('\\', '/')
MEDIA_URL = '/media/'
如果您在端口而非服务器上运行,请确保DEBUG
为True
。在Web服务器上保持False(nginix,apache等)。
验证urls.py中的以下语句
from django.conf import settings
from django.conf.urls.static import static
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL,document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
正如您在模型文件字段中提到的hiring/employees/photo/
路径一样,这必须存在于根文件夹中。
`hiring/employees/photo/` #Must be created at root of your project with permissions of 755.
是的,正如丹尼斯所说,media
文件夹也需要在根目录。用这条路。