ModelForm文件上传

一、 启用media

1、在url中进行配置:

from django.urls import path,re_path
from django.views.static import serve
from django.conf import settings

urlpatterns = [
    # path('admin/', admin.site.urls),
    # 配置media
    re_path(r'^media/(?P<path>.*)$',serve,{'document_root':settings.MEDIA_ROOT},name='media'),
]

2、在settings.py中配置:

import os
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
MEDIA_URL = '/media/'

# ModelForm文件上传
class City(models.Model):
	'''老板'''
	name = models.CharField(verbose_name='姓名', max_length=32)
	count = models.IntegerField(verbose_name='人口')
	# 本质上也是CharField,自动保存数据到media下的city/文件夹
	img = models.FileField(verbose_name='Logo', max_length=128,upload_to='city/')

二、定义modelForm

class UpModelForm(BootStrapModelForm):
	bootstrap_exclude_fields = ['img']
	class Meta:
		model = models.City
		fields = '__all__'

三、

def upload_model_form(request):
	'''上传文件和数据(modelForm)'''
	title = 'ModelForm上传文件'
	if request.method == 'GET':
		form = UpModelForm()
		return render(request, 'upload_form.html', {'form': form, 'title': title})
	form = UpModelForm(data=request.POST,files=request.FILES)
	if form.is_valid():
		# 对于文件:自动保存
		# 字段+路径保存到数据库
		form.save()
		return HttpResponse('OK')
	return render(request, 'upload_form.html', {'form': form, 'title': title})

手动上传

前端

 <div class="container">
    <form action="" method="post" enctype="multipart/form-data">
        {% csrf_token %}
        <input type="text" name="username">
        <input type="file" name="avatar">
        <input type="submit" value="提交">
    </form>
</div>

后端

def upload_list(request):
	if request.method == 'GET':
		return render(request, 'upload_list.html')
	# print(request.POST) # 请求体中数据
	# print(request.FILES)    # 请求发过来的文件
	file_object = request.FILES.get('avatar')
	print(file_object.name)

	f = open(file_object.name, mode='wb')
	for chunk in file_object.chunks():
		f.write(chunk)
	f.close()

	return HttpResponse('...')

forms上传文件

<div class="container">
    <div class="panel panel-default">
        <div class="panel-heading">
            <h3 class="panel-title">{{ title }}</h3>
        </div>
        <div class="panel-body">
            <form method="post" enctype="multipart/form-data" novalidate>
                {% csrf_token %}
                {% for field in form %}
                    <div class="form-group">
                        <label>{{ field.label }}</label>
                        {{ field }}
                        <span style="color:red;">{{ field.errors.0 }}</span>
                    </div>
                {% endfor %}
                <button type="submit" class="btn btn-primary">提交</button>
            </form>
        </div>
    </div>
</div>

from django import forms
from app01.utils.bootstrap import BootStrapForm


class UpForm(BootStrapForm):
	bootstrap_exclude_fields = ['img']
	name = forms.CharField(label='姓名')
	age = forms.IntegerField(label='年龄')
	img = forms.FileField(label='头像')


def upload_form(request):
	title = 'Form上传'
	if request.method == 'GET':
		form = UpForm()
		return render(request, 'upload_form.html', {'form': form, 'title': title})
	form = UpForm(data=request.POST, files=request.FILES)
	if form.is_valid():
		# 1.读取图片内容,写入到文件夹中获取文件的路径
		image_object = form.cleaned_data.get('img')
		from django.conf import settings

		# media_path = os.path.join(settings.MEDIA_ROOT, image_object.name) # 存储到数据库中的绝对路径
		media_path = os.path.join('media', image_object.name)  # 存储到数据库中的路径
		f = open(media_path, mode='wb')
		for chunk in image_object.chunks():
			f.write(chunk)
		f.close()
		# 2.将图片文件路径写入到数据库
		models.Boss.objects.create(
			name=form.cleaned_data['name'],
			age=form.cleaned_data['age'],
			img=media_path
		)

		return HttpResponse('...')
	return render(request, 'upload_form.html', {'form': form, 'title': title})
posted @ 2023-11-15 19:28  劼吉力劼  阅读(88)  评论(0)    收藏  举报