Django File Upload
Some interesting examples on how to handle file uploads using Django:
save()
method in the form class. This method is invoked when calling form.save()
, which is standard Django newforms practice. (Note that this snipped uses clean_data
. As of Django version 0.96, clean_data
has been renamed to cleaned_data
, so you will have to change the code or it won’t work) save_FOO_file
method. (This method is automatically provided by Django for fields declared as models.ImageField
or models.FileField
in the model. See the db-api documentation.) request.user
by calling form_for_instance
. The resulting class in then monkey-patched to insert the avatar image validation code. (Although the code is interesting the monkey patch seems unnecessary. I wouldn’t mind inserting the avatar validation method in a UserProfileForm
class derived from form.Forms
. The code would be certainly clearer: I think KISS takes precedence over DRY in this case.) Interesting, there seems to be no easy way of limiting the uploaded file size. The file can be rejected at validation time, but the data would have already been transfered.
A file upload recipe
After reading those posts, I think that a good recipe for handling file uploads in Django would be:
form.Forms
and declare a clean_FOO
method for each models.FileInput
or models.ImageInput
fields declared in the model class. These clean_FOO methods are used to validate the uploaded files. is_valid()
. request.FILES
object, by writing a save()
method for the subclassed form or by calling save_FOO_file
for the model instance. A simpler way to upload a file
The following short Django example uses no data models, does no data validation, and saves the file directly to disk using python standard file functions. It is just a simple test I wrote to get familiar with the
request.FILES
object. This is not production code: it could be used to execute an arbitrary script on the server. The directory where the file is to be saved must be writable by the user that is running the Django server script. (The example uses MEDIA_ROOT as defined in settings.py
.) file: views.py
view plain print ?
from django import http from django import newforms as forms from django.shortcuts import render_to_response from djangotest.settings import MEDIA_ROOT class SimpleFileForm(forms.Form): file = forms.Field(widget=forms.FileInput, required=False) def directupload(request): """Saves the file directly from the request object. Disclaimer: This is code is just an example, and should not be used on a real website. It does not validate file uploaded: it could be used to execute an arbitrary script on the server. """ template = 'fileupload.html' if request['method'] == 'POST': if 'file' in request.FILES: file = request.FILES['file'] # Other data on the request.FILES dictionary: # filesize = len(file['content'])
# filetype = file['content-type'] filename = file['filename'] fd = open('%s/%s' % (MEDIA_ROOT, filename), 'wb') fd.write(file['content']) fd.close() return http.HttpResponseRedirect(' upload_success.html') else: # display the form form = SimpleFileForm() return render_to_response(template, { 'form': form })
file: fileupload.html
view plain print ?
Upload a file
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.