django에서 form 폼을 통해 파일 업로드
5223 단어 django
python2.7
우선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}))
모델에서도 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)
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Django의 질문 및 답변 웹사이트환영 친구, 이것은 우리의 새로운 블로그입니다. 이 블로그에서는 , 과 같은 Question-n-Answer 웹사이트를 만들고 있습니다. 이 웹사이트는 회원가입 및 로그인이 가능합니다. 로그인 후 사용자는 사용자의 ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.