我有一个用FileField()
呈现的表单
提交表单后,这就是我的看法。
def complete(request):
file = request.POST.get('my_uploaded_file')
...
get a instance of my object that this is saving to
...
inst.file = file
inst.save()
return render(request, 'myapp/mypage.html')
我的模型如下:
class MyUpload(models.Model):
file = models.FileField(blank=True, upload_to='user_uploads/')
还有我的表格
class myForm(forms.Form):
file = forms.FileField(label='File')
现在,当我选择一个文件并单击提交时,该文件将在模型中更新。当我尝试查看图像时,出现404错误。
这是在管理面板中将我链接到的链接
http://localhost:8000/media/Roku.pcapng
编辑:
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
我的模板已修改
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(MEDIA_ROOT)],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
文件结构
djang_project
-app1
-app2
-app3
-app4
-media
--my_templates
--profile_pics
--user_logs
-app5
-static
-app6
.gitignore
.manage.py
主要urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('register/', user_views.register, name='register'),
path('profile/', user_views.profile, name='profile'),
path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'),
path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout'),
path('adobe/', include('adobeparser.urls')),
path('segment/', include('jsonparser.urls')),
path('omega/', include('omegavalidator.urls')),
path('fsrevamp/', include('fsrevamp.urls')),
path('', root_views.home, name='root-home'),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
答案 0 :(得分:1)
我想我明白了。看来您正在尝试从request.POST获取文件,而应该从request.FILES获得文件,例如:
file = request.FILES.get('my_uploaded_file')
upload = MyUpload.objects.create(file=file)
upload.save()
...
或者:
form = myForm(request.POST, request.FILES)
if form.is_valid():
# do something with the file
文档:https://docs.djangoproject.com/en/3.0/topics/http/file-uploads/