django explicit method of uploading images to database after front end
- 2020-09-28 08:58:47
- OfStack
1. Use ImageField to install pillow module first
pip install pillow
2. Set in models of app
class Image(models.Model):
pic_name=models.CharField(' The picture ',max_length=40)
pic_path=models.ImageField(upload_to="pic_folder/",default='pic_folder/None/no_image.pig')
3. Set the method to get the image in view
def upload_pic(request):
pic=Image.objects.all()
return render(request,'blog/image.html',{'pic':pic})
4. Set in settings
1 , add media The template
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(os.path.dirname(__file__), 'templates'),os.path.join(os.path.dirname(__file__), 'static'), ],
'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',
],
},
},
]
2 , set media The path of the
MEDIA_URL='media/'
MEDIA_ROOT=os.path.join(BASE_DIR,'media').replace('\\','/')
5. Set in urls of app
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
url(r'^pic$', views.upload_pic, name='upload_pic')
]+static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
After logging in via admin and uploading images, a directory of media/pic_folder is generated under the site