File Upload:
File upload site development is a very common feature. Here in detail how to achieve file upload function in Django.
Distal HTML code to achieve:
1. In the front end, we need to fill in a form
label, then the form
specified label enctype="multipart/form-data"
, otherwise you can not upload files.
2. form
Add a label input
tag, and then specify input
a tag name
, and type="file"
.
Sample code above two steps as follows:
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="myfile">
</form>
The back-end code to achieve:
The main work is to receive back-end file. And then stored files. Way to receive the file with POST way to receive is the same, but is achieved through FILES. Sample code is as follows:
def save_file(file):
with open('somefile.txt','wb') as fp:
for chunk in file.chunks():
fp.write(chunk)
def index(request):
if request.method == 'GET':
form = MyForm()
return render(request,'index.html',{'form':form})
else:
myfile = request.FILES.get('myfile')
save_file(myfile)
return HttpResponse('success')
By the above code request.FILES
after receiving the file, and then written to the specified location. That way you can upload a file up.
Use models to handle file uploads:
In the definition of the model, we can assign fields to store files FileField
, this Field
can pass a upload_to
parameter to specify the file to upload up where. For example, we allow him to save the project files
folder, then the sample code as follows:
# models.py
class Article(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
thumbnail = models.FileField(upload_to="files")
# views.py
def index(request):
if request.method == 'GET':
return render(request,'index.html')
else:
title = request.POST.get('title')
content = request.POST.get('content')
thumbnail = request.FILES.get('thumbnail')
article = Article(title=title, content=content, thumbnail=thumbnail)
article.save()
return HttpResponse('success')
End call the article.save()
method, it will save the file to files
the following, and path of the file will be stored in the database.
Designated MEDIA_ROOT and MEDIA_URL:
Above we are using the upload_to
directory to upload the file specified. We can also specify MEDIA_ROOT
, you do not need FielField
to specify in upload_to
, he will automatically upload files to a MEDIA_ROOT
directory.
settings.py
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
MEDIA_URL = '/media/'
Then we can add the access path under MEDIA_ROOT directory urls.py in. Sample code is as follows:
from django.urls import path
from front import views
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
path('', views.index),
] + static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
If you specify MEDIA_ROOT
, and upload_to
then upload the files to MEDIA_ROOT
in the upload_to
folder. Sample code is as follows:
class Article(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
thumbnail = models.FileField(upload_to="%Y/%m/%d/")
Limit uploaded filename extension:
If you want to limit the expansion of the uploaded file name, then we need to use the form to be limited. We can use the normal Form
form, it can also be used ModelForm
to read the field directly from the model. Sample code is as follows:
# models.py
class Article(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
thumbnial = models.FileField(upload_to='%Y/%m/%d/',validators=[validators.FileExtensionValidator(['txt','pdf'])])
# forms.py
class ArticleForm(forms.ModelForm):
class Meta:
model = Article
fields = "__all__"
upload image:
Upload pictures with a normal file upload is the same. Just upload the picture when Django will determine whether the uploaded file is a picture format (except judgment extension, it will determine whether the available picture). If not, it will fail validation. We first define a first included ImageField
the model. Sample code is as follows:
class Article(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
thumbnail = models.ImageField(upload_to="%Y/%m/%d/")
To verify whether it is qualified as a picture, so we need to use a form to be verified. We use the form directly ModelForm
on it. Sample code is as follows:
class MyForm(forms.ModelForm):
class Meta:
model = Article
fields = "__all__"
Note: Use ImageField, you must first install Pillow library: pip install pillow