当前位置:   article > 正文

django文件上传简单配置_动态文件上传django播放配置

动态文件上传django播放配置

1.models

model:

class Post(models.Model):
    image=models.FileField(null=True,blank=True)
  • 1
  • 2

settings:

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
  • 1
  • 2

admin:

class Imageadmin(admin.ModelAdmin):
    list_display = ("image"),
    
admin.site.register(Post,Imageadmin)
  • 1
  • 2
  • 3
  • 4

urls:

from django.views.static import serve

re_path(r"^media/(.*)/", serve, {"document_root": settings.MEDIA_ROOT}),
  • 1
  • 2
  • 3

在这里插入图片描述

2.forms.Form

form:

from django import forms


class UploadFileForm(forms.Form):
    file=forms.FileField()
  • 1
  • 2
  • 3
  • 4
  • 5

views:

def fileupload(request):
    if request.method=='POST':
        #这个file与form中的名称对应
        uploadfile = request.FILES.get('file', None)
        form =UploadFileForm(request,request.FILES)
        if form.is_valid():
            file_path = os.path.join(MEDIA_ROOT, uploadfile.name)
            if handle_file(file_path,uploadfile):
                res = {'code': 0, 'msg': 'ok'}
                return JsonResponse(res)
            else:
                res = {'code': 1, 'msg': 'error'}
                return JsonResponse(res)
    else:
        form=UploadFileForm()
        return render(request,'upload.html',locals())

def handle_file(file_path,file):
    try:
        with open(file_path,'wb') as f:
            for i in file.chunks():
                f.write(i)
    except Exception as e:
        print(e)
        return False
    return True
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26

urls:

path('uploads/',views.fileupload,name='uploads'),
  • 1

templates:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="{% url 'apps:uploads' %}" method="post" enctype="multipart/form-data">
    {% csrf_token %}
    {{ form }}
    <br/>
    <input type="submit" name="提交">
</form>
</body>
</html>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

在这里插入图片描述

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/爱喝兽奶帝天荒/article/detail/938263
推荐阅读
相关标签
  

闽ICP备14008679号