需求描述:
使用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)
- 添加如下代码,设置路由
- 最后打开[app名]下的models.py:
- 在Question类中添加如下代码:
avatar = models.FileField(upload_to='polls/')
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
- 在Question类中添加如下代码:
- 最最后,执行【python manage.py makemigrations】和【python manage.py migrate】两条命令,进行表结构更改,迁移。
- 重启服务器后登陆admin,选择Question,选择ADD QUESTION,选择必须的信息和图片后,保存成功,可以在后台看到添加的图片了,也通过MEDIA_URL加路径访问已经上传的图片
参考(感谢):
https://www.jianshu.com/p/f819db65e6a3