django form表单上传文件

1,前端页面

form表单上加:
    enctype="multipart/form-data"
type类型:file
     <input type="file" class="btn btn-primary btn-lg active" name="imgdetail"/>
 
  
 <form class="form-horizontal" action="{% url 'pro:start_step' %}" method="post" enctype="multipart/form-data" >
                {% csrf_token %}
              <div class="form-group">
                <label class="col-sm-2 control-label">项目详情label>
                <div class="col-sm-10">

                  <input type="file" class="btn btn-primary btn-lg active" name="imgdetail"/>上传图片
                  <label class="control-label">支持jpg、jpeg、png、gif格式,大小不超过2M,建议尺寸:宽740pxlabel>
                div>
              div>
                    <button type="submit" class="btn  btn-warning btn-lg" id="next">下一步button>
                div>
            form>

2,forms验证

   / forms.py

from django import forms
class FilesForm(forms.Form):
    img = forms.FileField(required=False)
    img_detail = forms.FileField(required=False)

3,view视图

   // project model

//type = models.ForeignKey(Type,verbose_name='类型',blank=True,null=True)

    

class Start_Step(View):

    def get(self,request):
        return render(request,'start-step-1.html')

    def post(self,request):
        #表单验证
        form = FilesForm(request.POST or None, request.FILES or None)
        if form.is_valid():
            img = form.cleaned_data['img']
            img_detail = form.cleaned_data['img_detail']
            project_name = request.POST.get('project_name') #项目名
            project_desc = request.POST.get('project_desc')#项目描述
            money = request.POST.get('money')#项目金额
            days = request.POST.get('days') #筹集天数

            project = Project()
            project.name = project_name
            project.money = money
            project.late_day = days
            project.remark = project_desc
            project.status = '0'
            project.supportmoney = 1000
            type = Type(id=1) 
            project.type = type
            project.img = img
            project.img_detail = img_detail
            project.save()
            return render(request, 'start-step-2.html',{'project_id':project.id})


    

你可能感兴趣的:(django)