English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

تحميل ملفات في Django

برای برنامه‌های وب، تا بتوانند فایل‌ها را (تصاویر، موسیقی، فرمت PDF، متون ...) آپلود کنند، معمولاً بسیار مفید است. بیایید در این بخش به بحث در مورد نحوه آپلود فایل‌ها با استفاده از Django بپردازیم.

آپلود تصاویر

قبل از شروع به توسعه آپلود تصاویر، مطمئن شوید که کتابخانه تصاویر Python (PIL) نصب شده است. حالا بیایید توضیح دهیم که چگونه تصاویر را آپلود کنیم، بیایید یک فایل پیکربندی ایجاد کنیم، در myapp/forms.py -

# Filename: example.py
# Copyright: 2020 By w3codebox
# Author by: ar.oldtoolbag.com
# Date: 2020-08-08
#-*- coding: utf-8 -*-
 من Django استيراد کنید
 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: ar.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: ar.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"]
          profile.picture = MyProfileForm.cleaned_data["picture"]
          profile.save()
          saved = True
    else:
       MyProfileForm = Profileform()
 
    return render(request, 'saved.htmll', locals())

لا تفوت هذا الجزء، قم بإنشاء ProfileForm و قمت ببعض التغييرات، أضفت ثاني parameter: request.FILES. إذا لم يتم التحقق من صحة النموذج سيتم الفشل، قدم رسالة تقول أن الصورة فارغة.

الآن، نحتاج فقط إلى نماذج saved.htmll و profile.htmll، النموذج والصفحة التحويلية−

myapp/templates/saved.htmll −

# Filename: example.py
# Copyright: 2020 By w3codebox
# Author by: ar.oldtoolbag.com
# Date: 2020-08-08
<html>
    <body>
       {% if saved %}
          <strong>تم حفظ ملفك الشخصي.</strong>
       {% endif %}
       {% if not saved %}
          <strong>لم يتم حفظ ملفك الشخصي.</strong>
       {% endif %}
    </body>
 </html>

myapp/templates/profile.htmll −

# Filename: example.py
# Copyright: 2020 By w3codebox
# Author by: ar.oldtoolbag.com
# Date: 2020-08-08
<html>
    <body>
       <form name = "form" enctype = "multipart/form-data" 
          action = "{% url "myapp.views.SaveProfile" %}" method = "POST" >{% csrf_token %}
          <div style = "max-width:470px;">
             <center> 
                <input type = "text" style = "margin-left:20%;" 
                placeholder = "اسم" name = "name" />
             </center>
          </div>
 
          <br>
          <div style = "max-width:470px;">
             <center> 
                <input type = "file" style = "margin-left:20%;" 
                   placeholder = "صورة" 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 = "تسجيل الدخول" >
                   <strong>تسجيل الدخول</strong>
                </button>
             </center>
          </div>
       </form>
    </body>
 </html>

في الخطوة التالية، سنحتاج إلى مطابقة عنوان URL لبدء: myapp/urls.py

# Filename: example.py
# Copyright: 2020 By w3codebox
# Author by: ar.oldtoolbag.com
# Date: 2020-08-08
من django.conf.urls import patterns, url
 من django.views.generic import TemplateView
 urlpatterns = patterns(
    'myapp.views', url(r'^profile/', TemplateView.as_view(),
       template_name = 'profile.htmll', url(r'^saved/', SaveProfile, name='saved')
 )

عند زيارة " /myapp/profile "، سنحصل على عرض النموذج التالي profile.htmll −

بعد تقديم الصيغة، سيتم عرض النماذج المحفوظة كما يلي −

في هذا المثال، سنقوم بشرح مثال تحميل الصور فقط، ولكن إذا كنت ترغب في تحميل نوع آخر من الملفات، فما عليك سوى تغيير حقل ImageField في هاتين النماذج وإضافة FileField إلى النموذج.