django to upload pictures to database and display them
- 2021-11-24 01:56:58
- OfStack
Django file upload for your reference, the specific content is as follows
Demand
1. Complete the student information registration operation
2. Put the student information into the warehouse
3. Store the uploaded file in the media folder under the project
4. Display all student information
Create a model class
class Student(models.Model):
sno = models.AutoField(primary_key=True)
sname = models.CharField(max_length=30)
photo = models.ImageField(upload_to='imgs')
<!-- Internal class writing Names in the database -->
class Meta:
db_table = 't_stu'
def __str__(self):
return self.sname
settings. py file upload related settings
INSTALLED_APPS = [
...
'stu'
]
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'django22',
'USER': 'root',
'PASSWORD': '123321',
'HOST': '127.0.0.1',
'PORT': '3306',
}
}
MEDIA_URL = '/media/'
<!-- Settings MEDIA_ROOT Default to null Image upload address in model class MEDIA_ROOT+up_load -->
<!--BASE_DIR Record for items -->
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
Map database table
# Knock a command in the terminal
python manage.py makemigrations test
python manage.py migrate
Configuring URL
Main route
from django.contrib import admin
from django.urls import path, re_path,include
from djurls.settings import MEDIA_ROOT
from stu import urls
from .import views
# Configure routing to read uploaded files behind the background
from django.views.static import serve
urlpatterns = [
path('test/',include('test.urls')),
re_path(r'^media/(?P<path>.*)/$', serve, {"document_root": MEDIA_ROOT}),
#server View function Will MEDIA And the template path of regular matching Show pictures
Sub-route
from django.urls import path
from test import views
urlpatterns = [
path('test/',views.index.as_view()),
path('show/',views.show)
]
Create a view
stu/views.py
import os
from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.shortcuts import render
from django.views import View
from djurls.settings import BASE_DIR
from test.models import Student
<!-- Pass as_view How to handle automatic acquisition requests -->
class index(View):
def get(self,request):
return render(request,'load.html')
def post(self,request):
name=request.POST.get('sname','')
photo=request.FILES.get('photo','')
age=request.POST.get('age','')
<!-- Carry out verification Split the suffix string of the file name Judge -->
extenedname=photo.name[photo.name.rindex('.')+1:]
allowedname=['jpg','png']
if extenedname not in allowedname:
return Http404()
stu=Student.objects.create(sname=name,age=20,photo=photo)
if stu:
return HttpResponse(' Successful registration ')
else:
return HttpResponseRedirect('/test/test/')
def show(request):
stulist=Student.objects.all()
return render(request,'show.html',{'stulist':stulist})
Create a template
templates/index. html registration interface
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/test/test/" method="post" enctype="multipart/form-data">
{% csrf_token %}
<p> Name <input type="text" name="sname"></p>
<p> Age <input type="number" name="age"></p>
<p> Photos <input type="file" name="photo"></p>
<input type="submit" value=" Registration ">
</form>
</body>
</html>
show. html Display Data Load Picture
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<table border="1px solid black" cellspacing="0px" width="500px" align="center">
<tr height="100px" align="center">
<td > Numbering </td>
<td > Name </td>
<td > Age </td>
<td > Head portrait </td>
</tr>
{% for stu in stulist %}
<tr height="100px" align="center">
<td >{{ forloop.counter }} </td>
<td >{{ stu.sname }}</td>
<td >{{ stu.age }}</td>
<td ><img src="/media/{{ stu.photo }}" alt=""></td>
<!-- Read photo Path of Access on the main route Pass server Process and display -->
</tr>
{% endfor %}
</table>
</body>
</html>