python3 django models保存filefiled字段统一目录、不修改文件名的方法

时间:2022-01-16 04:37:42

最经编写一个model时处理filefiled,使用post_form.save()进行新增和编辑文件保存位置不统一,如果出现重复文件名重复的话,上传文件名会被改名。

现有代码如下:

models.py

class Wechat_Pubno(models.Model):
name = models.CharField(verbose_name='名称*' , max_length=30 , blank=False , unique=True)
qr_code = models.ImageField(verbose_name='二维码', upload_to='upload/basicdata/wechat_pubno')
  def __str__(self):
    return self.name

forms.py

class Forms_Wechat_Pubno(forms.ModelForm):
def __init__(self , *args , **kwargs):
super(Forms_Wechat_Pubno , self).__init__(*args, **kwargs)
self.fields['qr_code'].required = False

class Meta :
model = Wechat_Pubno
fields = '__all__'

views.py
def add(request):
if request.method == 'POST':
post_form = forms(request.POST,request.FILES)
if post_form.is_valid():
post_form.save()
#配合post_form = forms(request.POST,request.FILES),web页面上传文件正常保存,而且不会重复
return HttpResponseRedirect(reverse('list_' + self.model_name))
else :
errors_message = post_form.errors
write_log('warning' , op_user, model_cnname + '新增失败' + str(post_form) + ',原因如下:\n' + str(errors_message))
return render(request, 'result.html', {'error_message': str(errors_message)})
else :
get_form = forms()
request_dict = {'title_name' : title_name , 'get_form': get_form}
return render(request, 'add_edit.html', request_dict)

改进views.py

def add(request):
if request.method == 'POST':
post_form = forms(request.POST,request.FILES)
if post_form.is_valid():
# 这段代码完全是为了处理filefiled,如果不需要使用filefiled的话,直接post_form.save()
media_dir = MEDIA_ROOT.replace(BASE_DIR + '/', '')
new_value = {}
for key in detail_field_list :
# 处理filefield
try :
if key in filefield_dict :
filename = key + '_' + str(request.FILES[key])
# 文件名,字段名+上传文件名
file = request.FILES[key]
upload_dir = MEDIA_ROOT + '/upload/' + app_name + '/' + model_name + '/' + request.POST.get('name') + '/'
# 上传目录,MEDIA_ROOT/upload/app名/modles名/字段name的值/

from library.webpage import uploadfile
fullfilename = uploadfile(file, filename, upload_dir)
# 最终目录为MEDIA_ROOT.replace(BASE_DIR,'')/upload/app名/modles名/字段name的值/字段名_上传文件名,防止出现重复替换操作
value = media_dir + '/upload/' + app_name + '/' + model_name + '/' + request.POST.get('name') + '/' + filename
# 数据库中写相对路径
else :
value = request.POST.get(key)
except :
value = request.POST.get(key)

# 日期转换
if re.search('^[0-9][0-9][0-9][0-9]/[0-1][0-9]', str(value)) :
from library.handle_datetime import date_convert
new_value[key] = date_convert(value , '%Y-%m-%d')
else:
new_value[key] = value

try :
import_models.objects.create(**new_value)
except Exception as e :
print('新增数据失败,' + str(new_value) + ',原因如下:\n' + str(e))

return HttpResponseRedirect(reverse('list_' + model_name))
else :
......
else :
......

edit函数类似


这样的话,可以统一,便于展示页面展示图片