- 设置settings.py
配置上传文件路径
# 配置静态文件
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static')
]
# 配置上传文件路径
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
- 设置上传图片数据库模型
class StudentInfo(models.Model):
i_addr = models.CharField(max_length=30)
#在用ImageField类型前要在虚拟环境里(pip install Pillow)
# 设置上传图片的数据类型(ImageField) (upload_to='upload')表示上传的url路径的文件名
i_image = models.ImageField(upload_to='upload', null=True)
s = models.OneToOneField(Student)
class Meta:
db_table = 'student_info'
- 处理上传图片的view方法为
def add_stu_info(request, stu_id):
if request.method == 'GET':
return render(request, 'addStuInfo.html', {'stu_id': stu_id})
# 添加头像图片,接收到img的url
img = request.FILES.get('img')
if request.method == 'POST':
stu_id = request.POST.get('stu_id')
addr = request.POST.get('addr')
# 把图片的路径保存在数据库中
StudentInfo.objects.create(i_addr=addr, s_id=stu_id, i_image=img)
return HttpResponseRedirect('/stu/index/')
- 返回数据的view方法
def index(request):
if request.method == 'GET':
stuinfos = StudentInfo.objects.all()
return render(request, 'index.html', {'stuinfos': stuinfos})
- 现在返回还无法显示图片,因为这些要在静态文件下才能显示出来,设置总项目的urls.py
from django.conf.urls import url, include
from django.contrib import admin
from django.contrib.staticfiles.urls import static
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'stu/', include('stu.urls', namespace='s')),
url(r'^uauth/', include('uauth.urls'))
]
# 把media设置为静态文件夹
from day51 import settings
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
- 返回数据的html页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>所有学生信息</title>
</head>
<body>
{% for stuinfo in stuinfos %}
姓名:{{ stuinfo.s.s_name }}
电话:{{ stuinfo.s.s_tel }}
地址:{{ stuinfo.i_addr }}
头像:
{% if stuinfo.i_image %}
<img src="/media/{{ stuinfo.i_image }}" width="100" height="100">
{% endif %}
<br>
{% endfor %}
<a href="{% url 's:add' %}">添加学生</a>
</body>
</html>
提交图片的html页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>添加学生详情页面</title>
</head>
<body>
<form action="" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<input type="hidden" value="{{ stu_id }}" name="stu_id">
地址:<input type="text" name="addr"> <br>
头像:<input type="file" name="img"> <br>
<input type="submit" value="提交">
</form>
</body>
</html