• django实现快速文件上传


    摘自http://www.cnblogs.com/fnng/p/3740274.html

    数据库

    from django.db import models
    
    # Create your models here.
    class User(models.Model):
        username = models.CharField(max_length = 30)
        headImg = models.FileField(upload_to = 'test/')  #注意是路径是跟在MEDIA_ROOT下
    
        def __unicode__(self):
            return self.username
    

    模板

    <?xml version="1.0" encoding="UTF-8"?> 
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <title></title>
    </head>
    <body>
    <h1>register</h1>
    <form method="post" enctype="multipart/form-data" >
    {{uf.as_p}}
    <input type="submit" value="ok"/>
    </form>
    </body>
    </html>
    

    视图

    #coding=utf-8
    from django.shortcuts import render,render_to_response
    from django import forms
    from django.http import HttpResponse
    from disk.models import User
    
    # Create your views here.
    class UserForm(forms.Form):
        username = forms.CharField()
        headImg = forms.FileField()
    
    def register(request):
        if request.method == "POST":
            uf = UserForm(request.POST,request.FILES)
            if uf.is_valid():
                #获取表单信息
                username = uf.cleaned_data['username']
                headImg = uf.cleaned_data['headImg']
                #写入数据库
                user = User()
                user.username = username
                user.headImg = headImg
                user.save()
                return HttpResponse('upload ok!')
        else:
            uf = UserForm()
        return render_to_response('register.html',{'uf':uf})
    

      

    csrf设置:setting.py中注释

    MIDDLEWARE_CLASSES = (
        'django.contrib.sessions.middleware.SessionMiddleware',
        'django.middleware.common.CommonMiddleware',
        #'django.middleware.csrf.CsrfViewMiddleware',
        'django.contrib.auth.middleware.AuthenticationMiddleware',
        'django.contrib.messages.middleware.MessageMiddleware',
        'django.middleware.clickjacking.XFrameOptionsMiddleware',
    )
    

      

  • 相关阅读:
    memory prefix out omni,over,out,od,octa ~O
    killl prefix out macro mis mal micro -m
    memory prefix mini mono multi out _m 5
    memory prefix inter,intra,intro,iso out 5
    memory prefix il ir im in out 3 i
    memory prefix twi,tri,trans ,tetra out 4
    memory prefix retro,re out 2
    memory prefix un,under,uni out1
    Python调用libsvm
    yolov3 训练数据集
  • 原文地址:https://www.cnblogs.com/songbird/p/5186199.html
Copyright © 2020-2023  润新知