Django implements image upload and display

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.