Lompat ke konten Lompat ke sidebar Lompat ke footer

How to Send Uploaded File From Django

Subscribe to our YouTube Channel!
[Jul 12, 2021] New Video: How to Use Django Rest Framework Permissions (DRF Tutorial - Part vii)


How to Upload Files With Django

How to Upload Files With Django

Updated at Nov 2, 2018: Equally suggested by @fapolloner, I've removed the manual file handling. Updated the instance using FileSystemStorage instead. Cheers!

In this tutorial y'all will larn the concepts backside Django file upload and how to handle file upload using model forms. In the end of this post you will observe the source code of the examples I used so you can try and explore.

This tutorial is also available in video format:


The Basics of File Upload With Django

When files are submitted to the server, the file information ends up placed in request.FILES.

It is mandatory for the HTML class to have the aspect enctype="multipart/course-data" set correctly. Otherwise the request.FILES will be empty.

The form must be submitted using the Post method.

Django have proper model fields to handle uploaded files: FileField and ImageField.

The files uploaded to FileField or ImageField are not stored in the database merely in the filesystem.

FileField and ImageField are created every bit a string field in the database (commonly VARCHAR), containing the reference to the actual file.

If you delete a model instance containing FileField or ImageField, Django will not delete the physical file, but but the reference to the file.

The request.FILES is a dictionary-like object. Each key in asking.FILES is the proper noun from the <input type="file" proper noun="" />.

Each value in request.FILES is an UploadedFile case.

You will need to fix MEDIA_URL and MEDIA_ROOT in your projection's settings.py.

                                  MEDIA_URL                  =                  '/media/'                  MEDIA_ROOT                  =                  os                  .                  path                  .                  join                  (                  BASE_DIR                  ,                  'media'                  )                              

In the development server you may serve the user uploaded files (media) using django.contrib.staticfiles.views.serve() view.

                                  from                  django.conf                  import                  settings                  from                  django.conf.urls.static                  import                  static                  urlpatterns                  =                  [                  # Project url patterns...                  ]                  if                  settings                  .                  DEBUG                  :                  urlpatterns                  +=                  static                  (                  settings                  .                  MEDIA_URL                  ,                  document_root                  =                  settings                  .                  MEDIA_ROOT                  )                              

To admission the MEDIA_URL in template you lot must add django.template.context_processors.media to your context_processeors inside the TEMPLATES config.


Elementary File Upload

Post-obit is a minimal file upload instance using FileSystemStorage. Use it just to larn near the flow of the procedure.

simple_upload.html

                {% extends 'base.html' %}  {% load static %}  {% block content %}                  <form                  method=                  "post"                  enctype=                  "multipart/form-information"                  >                  {% csrf_token %}                  <input                  type=                  "file"                  name=                  "myfile"                  >                  <button                  type=                  "submit"                  >Upload</push button>                  </form>                  {% if uploaded_file_url %}                  <p>File uploaded at:                  <a                  href=                  "{{ uploaded_file_url }}"                  >{{ uploaded_file_url }}</a></p>                  {% endif %}                  <p><a                  href=                  "{% url 'home' %}"                  >Return to home</a></p>                  {% endblock %}              

views.py

                                  from                  django.shortcuts                  import                  return                  from                  django.conf                  import                  settings                  from                  django.core.files.storage                  import                  FileSystemStorage                  def                  simple_upload                  (                  request                  ):                  if                  request                  .                  method                  ==                  'POST'                  and                  request                  .                  FILES                  [                  'myfile'                  ]:                  myfile                  =                  asking                  .                  FILES                  [                  'myfile'                  ]                  fs                  =                  FileSystemStorage                  ()                  filename                  =                  fs                  .                  save                  (                  myfile                  .                  proper noun                  ,                  myfile                  )                  uploaded_file_url                  =                  fs                  .                  url                  (                  filename                  )                  return                  render                  (                  request                  ,                  'core/simple_upload.html'                  ,                  {                  'uploaded_file_url'                  :                  uploaded_file_url                  })                  render                  render                  (                  request                  ,                  'core/simple_upload.html'                  )                              

File Upload With Model Forms

Now, this is a fashion more user-friendly mode. Model forms perform validation, automatically builds the absolute path for the upload, treats filename conflicts and other mutual tasks.

models.py

                                  from                  django.db                  import                  models                  course                  Document                  (                  models                  .                  Model                  ):                  description                  =                  models                  .                  CharField                  (                  max_length                  =                  255                  ,                  blank                  =                  True                  )                  certificate                  =                  models                  .                  FileField                  (                  upload_to                  =                  'documents/'                  )                  uploaded_at                  =                  models                  .                  DateTimeField                  (                  auto_now_add                  =                  Truthful                  )                              

forms.py

                                  from                  django                  import                  forms                  from                  uploads.cadre.models                  import                  Certificate                  class                  DocumentForm                  (                  forms                  .                  ModelForm                  ):                  class                  Meta                  :                  model                  =                  Certificate                  fields                  =                  (                  'description'                  ,                  'document'                  ,                  )                              

views.py

                                  def                  model_form_upload                  (                  asking                  ):                  if                  request                  .                  method                  ==                  'POST'                  :                  course                  =                  DocumentForm                  (                  request                  .                  POST                  ,                  request                  .                  FILES                  )                  if                  form                  .                  is_valid                  ():                  course                  .                  relieve                  ()                  return                  redirect                  (                  'dwelling'                  )                  else                  :                  form                  =                  DocumentForm                  ()                  return                  render                  (                  request                  ,                  'core/model_form_upload.html'                  ,                  {                  'form'                  :                  form                  })                              

model_form_upload.html

                {% extends 'base of operations.html' %}  {% cake content %}                  <class                  method=                  "post"                  enctype=                  "multipart/form-data"                  >                  {% csrf_token %}     {{ form.as_p }}                  <push button                  type=                  "submit"                  >Upload</push button>                  </course>                  <p><a                  href=                  "{% url 'domicile' %}"                  >Return to home</a></p>                  {% endblock %}              

Most the FileField upload_to Parameter

See the example beneath:

                                  certificate                  =                  models                  .                  FileField                  (                  upload_to                  =                  'documents/'                  )                              

Note the upload_to parameter. The files will be automatically uploaded to MEDIA_ROOT/documents/.

It is also possible to do something like:

                                  document                  =                  models                  .                  FileField                  (                  upload_to                  =                  'documents/                  %                  Y/                  %                  1000/                  %                  d/'                  )                              

A file uploaded today would be uploaded to MEDIA_ROOT/documents/2016/08/01/.

The upload_to tin also be a callable that returns a cord. This callable accepts two parameters, instance and filename.

                                  def                  user_directory_path                  (                  instance                  ,                  filename                  ):                  # file will be uploaded to MEDIA_ROOT/user_<id>/<filename>                  render                  'user_{0}/{i}'                  .                  format                  (                  instance                  .                  user                  .                  id                  ,                  filename                  )                  form                  MyModel                  (                  models                  .                  Model                  ):                  upload                  =                  models                  .                  FileField                  (                  upload_to                  =                  user_directory_path                  )                              

Download the Examples

The code used in this post is available on Github.

                git clone https://github.com/sibtc/simple-file-upload.git              
                pip install django              
                python manage.py migrate              
                python manage.py runserver              


deanfenii1989.blogspot.com

Source: https://simpleisbetterthancomplex.com/tutorial/2016/08/01/how-to-upload-files-with-django.html

Posting Komentar untuk "How to Send Uploaded File From Django"