Django 后台上传以及显示图片
2021-02-18 22:17
标签:utf-8 nbsp process image alt djang HERE 创建 content django 管理后台上传图片 2.创建app 3. project设定 urls.py 4. app 设定 admin.py urls.py views.py 5 . 前台设定 6. migraiton 7.进行管理后台上传user 图片http://localhost:8000/admin Django 后台上传以及显示图片 标签:utf-8 nbsp process image alt djang HERE 创建 content 原文地址:https://www.cnblogs.com/tingxin/p/12938921.html
1.安装pillowpip install Pillow
python manage.py startapp upload
settings.pyINSTALLED_APPS = [
‘django.contrib.admin‘,
‘django.contrib.auth‘,
‘django.contrib.contenttypes‘,
‘django.contrib.sessions‘,
‘django.contrib.messages‘,
‘django.contrib.staticfiles‘,
‘upload.apps.MyuploadConfig‘, #add this
]
TEMPLATES = [
{
‘BACKEND‘: ‘django.template.backends.django.DjangoTemplates‘,
‘DIRS‘: [os.path.join(BASE_DIR,‘templates‘)],
‘APP_DIRS‘: True,
‘OPTIONS‘: {
‘context_processors‘: [
‘django.template.context_processors.debug‘,
‘django.template.context_processors.request‘,
‘django.contrib.auth.context_processors.auth‘,
‘django.contrib.messages.context_processors.messages‘,
‘django.template.context_processors.media‘ #add this
],
},
},
]
#picture path setting
MEDIA_ROOT = os.path.join(BASE_DIR, ‘media‘).replace("\\", "/")
MEDIA_URL = ‘/media/‘
from django.contrib import admin
from django.urls import path,include
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
path(‘admin/‘, admin.site.urls),
path(‘‘, views.index),
path(‘upload/‘, include((‘myupload.urls‘, ‘myupload‘), namespace=‘myupload‘)), # add uppoad urls
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) #add image path
models.py from django.db import models
class User(models.Model):
name = models.CharField(verbose_name=‘姓名‘, max_length=10)
avator = models.ImageField(verbose_name=‘头像‘, upload_to=‘upload/%Y/%m/%d‘)
from django.contrib import admin
from .models import *
# Register your models here.
admin.site.register(User)
from django.contrib import admin
from django.urls import path, register_converter, re_path
from . import views
urlpatterns = [
path(‘‘, views.index, name=‘index‘), # 上传首页
]
from django.shortcuts import render
from .models import User
from django.http import HttpResponse
# Create your views here.
def index(request):
users = User.objects.all()return render(request, ‘upload/index.html‘, locals())
project 目录下 templates/upload/index.html
----------------------------------------------------------------------------------------DOCTYPE html>
html lang="en">
head>
meta charset="UTF-8">
title>Titletitle>
head>
body>
ul>
{% for user in users%}
li>{{ user.name }}li>
li>img src="{{ MEDIA_URL }}{{ user.avator }}" alt="">li>
{% endfor %}
ul>
body>
html>
python manage.py makemigrations
python manage.py migrate
python manage.py createsuperuser
python manage runserver 0.0.0.0:8000
8.显示 http://localhost:8000/upload/