django_上傳文件/圖像/圖片之settings.py的MEDIA_URL,MEDIA_ROOT,urls.py,models.py配置。

需求描述:

使用django寫了一個投票後臺,如果想給每個問題加一個圖片的話就需要用到MEDIA_URL,MEDIA_ROOT等等了。

整個過程需要用到[app名]下的models.py,[app名]下的urls.py,[app名]下的settings.py,出發!!

目前[app名]下的models.py的代碼如下:

from django.db import models
from django.utils import timezone
import datetime


# Create your models here.
class Question(models.Model):
    question_text = models.CharField(max_length=220)
    pub_date = models.DateTimeField("date published")

    def __str__(self):
        return self.question_text

    def was_published_recently(self):
        now = timezone.now()
        return now - datetime.timedelta(days=1) <= self.pub_date <= now

    was_published_recently.admin_order_field = "pub_date"
    was_published_recently.boolean = True
    was_published_recently.short_description = '是否最近發佈'

class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=220)
    count = models.IntegerField(default=0)

    def __str__(self):
        return self.choice_text

[app名]下的urls.py的代碼如下:

from django.contrib import admin
from django.urls import path, include
from mysite import settings
urlpatterns = [
    path('polls/', include("polls.urls")),
    path('admin/', admin.site.urls),

]

因爲settings中的內容過長,並且我們不需要進行修改,只是添加,所以就不將settings.py的代碼貼上了。

實現

  • 首先打開[app名]下的settings.py:
    • 添加兩個字段,分別爲【MEDIA_ROOT】,【MEDIA_URL】
# 設置上傳的文件的存放路徑
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
# 設置直接訪問上傳文件的url(訪問路徑)
MEDIA_URL = "/media/"

 

  • 其次打開[app名]下的urls.py:
    • 添加如下代碼,設置路由
      urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
      按住ctrl點擊static進入類中,執行return中內容設置路由
  •  最後打開[app名]下的models.py:
    • 在Question類中添加如下代碼:
      avatar = models.FileField(upload_to='polls/')
      完整models.py代碼如下:
      from django.db import models
      from django.utils import timezone
      import datetime
      
      
      # Create your models here.
      class Question(models.Model):
          question_text = models.CharField(max_length=220)
          pub_date = models.DateTimeField("date published")
          avatar = models.FileField(upload_to='polls/')
      
          def __str__(self):
              return self.question_text
      
          def was_published_recently(self):
              now = timezone.now()
              return now - datetime.timedelta(days=1) <= self.pub_date <= now
      
          was_published_recently.admin_order_field = "pub_date"
          was_published_recently.boolean = True
          was_published_recently.short_description = '是否最近發佈'
      
      class Choice(models.Model):
          question = models.ForeignKey(Question, on_delete=models.CASCADE)
          choice_text = models.CharField(max_length=220)
          count = models.IntegerField(default=0)
      
          def __str__(self):
              return self.choice_text
      

       

  •  最最後,執行【python manage.py makemigrations】和【python manage.py migrate】兩條命令,進行表結構更改,遷移。
  • 重啓服務器後登陸admin,選擇Question,選擇ADD QUESTION,選擇必須的信息和圖片後,保存成功,可以在後臺看到添加的圖片了,也通過MEDIA_URL加路徑訪問已經上傳的圖片

參考(感謝):

https://www.jianshu.com/p/f819db65e6a3

  •  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章