赞
踩
class Post(models.Model):
image=models.FileField(null=True,blank=True)
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
class Imageadmin(admin.ModelAdmin):
list_display = ("image"),
admin.site.register(Post,Imageadmin)
from django.views.static import serve
re_path(r"^media/(.*)/", serve, {"document_root": settings.MEDIA_ROOT}),
from django import forms
class UploadFileForm(forms.Form):
file=forms.FileField()
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
path('uploads/',views.fileupload,name='uploads'),
<!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>
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。