1 class ModelFormUploadFile(models.Model): 2 '''ModelForm测试上传文件''' 3 name = models.FileField(upload_to=settings.MEDIA_ROOT) 4 5 class Meta: 6 db_table = 'cmdbmgr_modelformuploadfile' 7 verbose_name = 'ModelForm测试文件上传' 8 verbose_name_plural = verbose_name 9 10 11 from django import forms 12 from django.views.generic import TemplateView 13 14 class UploadFileForm(forms.ModelForm): 15 class Meta: 16 model = ModelFormUploadFile 17 fields = '__all__' 18 19 class UploadFileView(TemplateView): 20 '''使用modelform方法上传文件''' 21 template_name = 'upload_file.html' 22 def get(self, request, *args, **kwargs): 23 '''渲染初始modelform''' 24 context = self.get_context_data() 25 context['form'] = UploadFileForm() 26 return self.render_to_response(context) 27 28 def post(self, request): 29 '''提高''' 30 form = UploadFileForm(request.POST, request.FILES) 31 if form.is_valid(): 32 form.save() 33 return HttpResponse('ok') 34 return HttpResponse('faild')