最近OA接了个需求其中是关于上传文件
首先是form中的代码,这里做了一个判断,判断是正确文件格式结尾的
class CreateForm(forms.Form):
attachment = forms.FileField(
label=u'申报材料',
max_length=256,
error_messages={'required': u'请上传附件!', 'max_length': u'ppt标题长度过长'}
)
def clean_attachment(self):
attachment = self.cleaned_data.get('attachment')
if str(attachment).split('.')[-1] not in ['ppt', 'pptx', 'xls', 'xlxs', 'pdf', 'doc', 'docx']:
raise forms.ValidationError(u'请上传正确的文件格式')
return attachment
views当中
这边要导入settings
from django.conf import settings
def handle_uploaded_file(f, path):
allpath = os.path.join(settings.MEDIA_ROOT, path)
if not os.path.exists(allpath):
os.makedirs(allpath, 0o777)
path_filename = os.path.join(allpath, str(f)).replace('\\', '/')
with open(path_filename, 'wb') as destination:
for chunk in f.chunks():
destination.write(chunk)
@login_required
def createresource(request):
form = CreateForm()
if request.method == 'POST':
form = CreateForm(request.POST, request.FILES)
if form.is_valid():
attachment = request.FILES['attachment']
path = os.path.join('resource/%s' % request.user.username)
handle_uploaded_file(attachment, path)
#我这边有一个判断是否是管理员登陆
try:
staff = Staff.objects.get(user=request.user)
except Exception:
if request.user.nickname == 'ROOT':
staff = Staff.objects.get(user_id=2)
else:
logger.info('User and Staff not match, user:%s' % request.user)
return HttpResponseRedirect(reverse('unlinkpermissionurl'))
try:
Resource.objects.create(
filename=str(attachment),
attachment=os.path.join(path, str(attachment)).replace('\\', '/'),
)
logger.info('resource create, by:%s' % request.user)
form = CreateResourceForm()
kwvars = {
'request': request,
'form': form,
'success_message': u'资源配置已提交.'
}
#抛错
except Exception as e:
logging.exception(e)
logger.info(' create failed, by:%s' % request.user)
kwvars = {
'request': request,
'form': form,
'error_message': u'提交失败,请联系管理员或稍后再试.'
}
return render_to_response("resource/resource_create.html", kwvars, RequestContext(request))
kwvars = {
'request': request,
'form': form,
}
return render_to_response("resource/resource_create.html", kwvars, RequestContext(request))
settings
if DEBUG is False:
STATIC_ROOT = os.path.join(BASE_DIR, 'static').replace('\\', '/')
# 如果MEDIA_ROOT配置在DEBUG为False时,开发模式下将需要访问/media/media/目录下的文件才能正常访问
MEDIA_ROOT = os.path.join(BASE_DIR, 'media').replace('\\', '/')
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
os.path.join(BASE_DIR, 'media'),
)
url,根据自己的来修改
url(r'^media/(?P.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT})
# url(r'^static/(?P.*)$', 'django.views.static.serve', { 'document_root': settings.STATIC_ROOT,}),
]
if settings.DEBUG is False:
urlpatterns.append(url(r'^static/(?P.*)$', 'django.views.static.serve',
{'document_root': settings.STATIC_ROOT}))
model中,这里也需要导入settings
from django.conf import settings
from django.db import models
import datetime
from django.contrib.auth.models import BaseUserManager, AbstractBaseUser
def attachment_path(instance, filename):
"""
Provide a file path that will help prevent files being overwritten, by
putting attachments in a folder off attachments for ticket/followup_id/.
"""
import os
#自定义路径
att_path = os.path.join('media/resource/%s' % instance.proposer.username)
if settings.DEFAULT_FILE_STORAGE == "django.core.files.storage.FileSystemStorage":
if not os.path.exists(att_path):
os.makedirs(att_path, 0o777)
return os.path.join(att_path, filename)
class Resource (models.Model):
attachment = models.FileField(max_length=256)