首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往
您找到你想要的搜索结果了吗?
是的
没有找到

django之文件上传下载等相关

实现步骤: 1)创建项目Django_upload:django-admin startproject Django_upload;创建app:cd Django_upload;python manage.py startapp blog。 2)设计模型(M) 这里的模型只包括了两个属性:用户名(即谁上传了该文件);文件名。具体形式如下所示: #coding=utf-8 from __future__ import unicode_literals from django.db import models class NormalUser(models.Model): username=models.CharField('用户名',max_length=30) #用户名 headImg=models.FileField('文件',upload_to='./upload')#文件名 def __str__(self): return self.username class Meta: ordering=['username']#排序风格username 同步数据库:Python manage.py makemigrations python manage.py migrate 3)设计视图(V) view.py: #coding=utf-8 from django.shortcuts import render,render_to_response from django import forms from django.http import HttpResponse from blog.models import * # Create your views here. class NormalUserForm(forms.Form): #form的定义和model类的定义很像 username=forms.CharField() headImg=forms.FileField() #在View中使用已定义的Form方法 def registerNormalUser(request): #刚显示时调用GET方法 if request.method=="POST": uf = NormalUserForm(request.POST,request.FILES)#刚显示时,实例化表单(是否有数据) if uf.is_valid():#验证数据是否合法,当合法时可以使用cleaned_data属性。 #用来得到经过'clean'格式化的数据,会所提交过来的数据转化成合适的Python的类型。 username = uf.cleaned_data['username'] headImg = uf.cleaned_data['headImg'] #write in database normalUser=NormalUser()#实例化NormalUser对象 normalUser.username = username normalUser.headImg = headImg normalUser.save()#保存到数据库表中 return HttpResponse('Upload Succeed!')#重定向显示内容(跳转后内容) else: uf=NormalUserForm()#刚显示时,实例化空表单 return render(request,'register.html',{'uf':uf})#只有刚显示时才起作用 配置urls.py: from django.conf.urls import url from django.contrib import admin from blog.views import * urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^register/$',registerNormalUser), ] 4)设计模板与表单(T)templates/register.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="

03

Django上传文件代码

在django里面上传文件 views.py # Create your views here. # coding=utf-8 from django.http import HttpResponse,HttpResponseRedirect from django.shortcuts import render_to_response from django.template import RequestContext from django.views.decorators.csrf import csrf_exempt from django.views.decorators.csrf import csrf_protect #上传文件 @csrf_exempt @csrf_protect def upload_tomcat_config_file(request):     from django import forms     class UploadFileForm(forms.Form):         title = forms.CharField(max_length=1000000)         file = forms.FileField()     if request.method == "GET":         data='get'     if request.method == "POST":         f = handle_uploaded_file(request.FILES['t_file'])     return render_to_response('upload_config_file.html',context_instance=RequestContext(request))     #return HttpResponse(data) def handle_uploaded_file(f):     f_path='/srv/salt/config/'+f.name     with open(f_path, 'wb+') as info:         print f.name         for chunk in f.chunks():             info.write(chunk)     return f #上传文件结束

01
领券