django에서 form 폼을 통해 파일 업로드

5223 단어 django
최근에 OA에서 요청이 들어왔는데 그중에 업로드에 관한 거예요.
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)

좋은 웹페이지 즐겨찾기