我正在使用ModelForms和通用编辑视图(创建,更新,删除)。我在本练习中的目标之一是了解一些框架(Django + Bootstrap +一个插件(例如PDF.js))并使用尽可能少的自定义代码。
我可以通过管理站点创建“文档”记录,上传保存在我设置的“文件”位置。当我尝试浏览我的网站时,没有上传任何文件,但其他字段将被更新(显然表单已验证)。 (FileField可以为空,因为我希望能够拥有指向非数字资产的指针)。相关代码:
# models.py
class document(models.Model):
ref_file = models.FileField(upload_to='documents/', blank=True, null=True)
def get_absolute_url(self):
return reverse('knowledge_manager:doc_detail', kwargs={'pk': self.pk})
# urls.py
urlpatterns = [
url(r'^doc$', views.docIndex.as_view(), name='doc_index'),
url(r'^doc/(?P<pk>\w+)/det', views.docUpdate.as_view(), name='doc_detail'),
url(r'^doc/new/$', views.docCreate.as_view(), name='doc_create'),
url(r'^doc/(?P<pk>\w+)/update', views.docUpdate.as_view(), name='doc_update'),
url(r'^doc/(?P<pk>\w+)/del', views.docDelete.as_view(), name='doc_delete')
]
# views.py
class docIndex(generic.ListView):
model = document
template_name = 'knowledge_manager/_index.html'
context_object_name = 'document_set'
class doc_detail(generic.DetailView):
model = reference
template_name = 'knowledge_manager/doc_detail.html'
context_object_name = 'document'
form_class = doc_form
success_url = reverse_lazy('knowledge_manager:doc_index')
class docCreate(generic.CreateView):
model = document
template_name = 'knowledge_manager/doc_detail.html'
form_class = doc_form
success_url = reverse_lazy('knowledge_manager:doc_index')
class docUpdate(generic.UpdateView):
model = document
template_name = 'knowledge_manager/doc_detail.html'
context_object_name = 'document'
form_class = doc_form
success_url = reverse_lazy('knowledge_manager:doc_index')
class docDelete(generic.DeleteView):
model = document
success_url = reverse_lazy('knowledge_manager:doc_index')
# forms.py
class doc_form(ModelForm):
class Meta:
model = document
fields = '__all__'
问题:
答案 0 :(得分:0)
我忽略了这个解决方案(stackoverflow),它指出表单需要此标记才能正确地将材料发送到request.FILES。
<form action="" method="post" **enctype="multipart/form-data"**>