django上传与显示图片

参考文章:https://www.jianshu.com/p/a3fb31f49f2e

功能:从后台admin上传图片,显示到前端页面

1、models.py

添加:  img = models.ImageField(upload_to='./img/', blank=True) 

class Post(models.Model):
    title = models.CharField(max_length=50)
    body = models.TextField()
    created_time = models.DateTimeField()
    modified_time = models.DateTimeField()
    experpt = models.CharField(max_length=200)
    category = models.ForeignKey('Category', on_delete=models.CASCADE)
    tags = models.ManyToManyField(Tag)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    img = models.ImageField(upload_to='./img/', blank=True, null=True)  #添加的img

    def __str__(self):
        return self.title

执行命令:

python manage.py makemigrations

python manage.py migrate

2、settings.py

添加:

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media').replace("//", "/")

3、项目的urls.py

添加:   +static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

如下:

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'', include('blog.urls', namespace='blog')),
]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

4、index.html 显示图片

 {% for comic in comic_list %}
         
  •                                      

    {{ comic.experpt }}

               
  •   {% endfor %}

    5、python manage.py runserver

    在后台添加图片,查看index.html图片显示成功

    你可能感兴趣的:(django)