English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
웹 애플리케이션에서 파일(자료 이미지, 음악, PDF 형식, 텍스트 등)을 업로드할 수 있도록 하기 위해, 일반적으로 매우 유용합니다. 이 장에서는 Django를 사용하여 파일을 업로드하는 방법에 대해 논의해 보겠습니다.
이미지 업로드 개발을 시작하기 전에, Python 이미지 라이브러리(PIL)가 설치되어 있는지 확인해 주세요. 지금부터 이미지 업로드에 대해 설명해 보겠습니다. 먼저 설정 파일 형식을 만들어 보겠습니다. myapp/forms.py -
# Filename : example.py # Copyright : 2020 By w3codebox # Author by : ko.oldtoolbag.com # Date : 2020-08-08 #-*- coding: utf-8 -*- from django import forms class ProfileForm(forms.Form): name = forms.CharField(max_length= 100) picture = forms.ImageFields()
正如你所看到的,这里的主要区别仅仅是 forms.ImageField。ImageField字段将确保上传的文件是一个图像。如果不是,格式验证将失败。
现在,让我们创建一个 "Profile" 模型,以保存上传的资料。在 myapp/models.py -
# Filename : example.py # Copyright : 2020 By w3codebox # Author by : ko.oldtoolbag.com # Date : 2020-08-08 from django.db import models class Profile(models.Model): name = models.CharField(max_length= 50) picture = models.ImageField(upload_to='pictures') class Meta: db_table = "profile"
正如所看到的模型,ImageField 使用强制性参数:upload_to. 这表示硬盘驱动器,图像保存所在的地方。注意,该参数将被添加到 settings.py文件中定义的MEDIA_ROOT选项。
现在我们有表单和模型,让我们来创建视图,在 myapp/ views.py -
# Filename : example.py # Copyright : 2020 By w3codebox # Author by : ko.oldtoolbag.com # Date : 2020-08-08 #-*- coding: utf-8 -*- from myapp.forms import ProfileForm from myapp.models import Profile def SaveProfile(request): saved = False if request.method == "POST": #Get the posted form MyProfileForm = ProfileForm(request.POST, request.FILES) if MyProfileForm.is_valid(): profile = Profile() profile.name = MyProfileForm.cleaned_data["name"]
myapp//
# Filename : example.py # Copyright : 2020 By w3codebox # Author by : ko.oldtoolbag.com # Date : 2020-08-08 /strong> /strong> </body> </html>
myapp//
# Filename : example.py # Copyright : 2020 By w3codebox # Author by : ko.oldtoolbag.com # Date : 2020-08-08 /- action="{% url 'myapp.views.SaveProfile' %}" method="POST" <div style="max-width:470px;"> <center> <input type="text" style="margin-left:20%;" placeholder="Name" name="name" /> </center> </div> <br> <div style="max-width:470px;"> <center> <input type="file" style="margin-left:20%;" placeholder="Picture" name="picture" /> </center> </div> <br> <div style="max-width:470px;"> <center> <button style="border:0px;background-color:#4285F4; margin-top:8%; height:35px; width:80%; margin-left:19%;"type="submit" value="Login" <strong>Login</strong> </button> </center> </div> </form> </body> </html>
다음은 URL을 매칭하여 시작해야 합니다 - myapp/urls.py
# Filename : example.py # Copyright : 2020 By w3codebox # Author by : ko.oldtoolbag.com # Date : 2020-08-08 from django.conf.urls import patterns, url urlpatterns = patterns( /', TemplateView.as_view( template_name = 'profile.htmll')), url(r'^saved',/', 'SaveProfile', name = 'saved') )
접근할 때/myapp/"profile"이라면, 아래 profile.htmll 템플릿이 표시됩니다 -
양식을 제출한 후, 저장된 템플릿은 다음과 같이 표시됩니다 -
이곳에서는 이미지 업로드 예제만 설명하지만, 다른 유형의 파일을 업로드하려면 ImageField를 이 두 모델과 FileField 폼에 변경하면 됩니다.