File Upload Flashcards
Configure For file upload
Create media directory
On settings: under static add MEDIA_URL = ‘/media/‘
add MEDIA_ROOT = os.path.join( BASE_DIR, ‘media’)
Media_root → tells Django where to look For media files are stored in file system
Url.py
Add
if settings. DEBUG:
url patterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Implementing upload feature
On models.py
Image = models.ImageField(upload_to=‘appname/image’)
* since we are working with images we need to install pillow*
Pip install pillow
*migrate
# use FileField for other files
On the template
<form method=‘post’ encrypt=multiparty/form-data>
{% csrf_token%}
{{form.as_p }}
</form>
Uploading files offer than images
On models.py
File = models.FileField(upload_to=‘app_name/files’)
Creating A form
Create forms.py
Class uploadForm(forms.ModelForm):
class meta:
Model = [model name]
fields = [name of fields]
Views.py
def upload_Image(request):
if request.method == ‘POST’:
form = uploadForm( request.POST, request.FILES)
If form. is_valid:
form. save()
saved_object = form. instance # get uploaded file
return render(request,’template_name’, {‘form’: form, ‘file’:saved_object}
else:
form = UploadForm()
return render …..