First install the Pillow module
Set under models.py
Class notices (models. Model):
Noticecategory=models. Charfield (max_length=10,default= ") #新闻分类
Noticeimagepath=models. ImageField (upload_to= ' img ')
The upload_to here refers to where the picture is stored
To set a method for getting pictures in views.py
def index (Request): notice_list = Notices.objects.all (). order_by (' Noticedata ') [:] return render (Request, ' index.html ', {' notice_list ': notice_list})
I am here to get the entire notices list.
Set in setting:
Media_root = Os.path.join (base_dir, ' media '). replace (' \ \ ', '/') #设置静态文件路径为主目录下的media文件夹MEDIA_URL = '/media/'
The media folder is automatically generated when uploading images
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 in URLs
Urlpatterns = [ url (' admin/', admin.site.urls), url (r ' ^std_web/', include (' Std_web.urls ', namespace= ' std_ Web '),]+ static (settings. Media_url, Document_root=settings. Media_root)
In the index.html
<a href= "{{notice_list. Noticeimagepath.url}} "></img></a>
Display the image code.
Django implements image upload and display