Skip to content Skip to sidebar Skip to footer

Django Upload Document Html to Open an Upload Window

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


How to Upload Files With Django

How to Upload Files With Django

Updated at November ii, 2018: As suggested by @fapolloner, I've removed the manual file handling. Updated the case using FileSystemStorage instead. Thank you!

In this tutorial you volition learn the concepts backside Django file upload and how to handle file upload using model forms. In the stop of this post you volition observe the source lawmaking of the examples I used so you tin endeavour and explore.

This tutorial is also available in video format:


The Nuts of File Upload With Django

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

It is mandatory for the HTML form to accept the aspect enctype="multipart/form-data" prepare correctly. Otherwise the request.FILES will be empty.

The form must exist submitted using the Mail method.

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

The files uploaded to FileField or ImageField are non stored in the database but in the filesystem.

FileField and ImageField are created as a cord field in the database (unremarkably VARCHAR), containing the reference to the actual file.

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

The request.FILES is a dictionary-similar object. Each key in request.FILES is the name from the <input type="file" name="" />.

Each value in request.FILES is an UploadedFile case.

You will demand to set MEDIA_URL and MEDIA_ROOT in your projection's settings.py.

                                  MEDIA_URL                  =                  '/media/'                  MEDIA_ROOT                  =                  os                  .                  path                  .                  bring together                  (                  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 access the MEDIA_URL in template you must add django.template.context_processors.media to your context_processeors inside the TEMPLATES config.


Unproblematic File Upload

Following is a minimal file upload case using FileSystemStorage. Use information technology but to larn most the flow of the process.

simple_upload.html

                {% extends 'base.html' %}  {% load static %}  {% block content %}                  <form                  method=                  "post"                  enctype=                  "multipart/class-information"                  >                  {% csrf_token %}                  <input                  type=                  "file"                  name=                  "myfile"                  >                  <button                  blazon=                  "submit"                  >Upload</button>                  </grade>                  {% 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                  render                  from                  django.conf                  import                  settings                  from                  django.cadre.files.storage                  import                  FileSystemStorage                  def                  simple_upload                  (                  asking                  ):                  if                  asking                  .                  method                  ==                  'POST'                  and                  request                  .                  FILES                  [                  'myfile'                  ]:                  myfile                  =                  asking                  .                  FILES                  [                  'myfile'                  ]                  fs                  =                  FileSystemStorage                  ()                  filename                  =                  fs                  .                  save                  (                  myfile                  .                  name                  ,                  myfile                  )                  uploaded_file_url                  =                  fs                  .                  url                  (                  filename                  )                  return                  render                  (                  request                  ,                  'cadre/simple_upload.html'                  ,                  {                  'uploaded_file_url'                  :                  uploaded_file_url                  })                  return                  render                  (                  request                  ,                  'core/simple_upload.html'                  )                              

File Upload With Model Forms

At present, this is a way more convenient way. Model forms perform validation, automatically builds the accented path for the upload, treats filename conflicts and other common tasks.

models.py

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

forms.py

                                  from                  django                  import                  forms                  from                  uploads.core.models                  import                  Document                  class                  DocumentForm                  (                  forms                  .                  ModelForm                  ):                  course                  Meta                  :                  model                  =                  Certificate                  fields                  =                  (                  'clarification'                  ,                  'document'                  ,                  )                              

views.py

                                  def                  model_form_upload                  (                  request                  ):                  if                  request                  .                  method                  ==                  'POST'                  :                  course                  =                  DocumentForm                  (                  asking                  .                  POST                  ,                  request                  .                  FILES                  )                  if                  form                  .                  is_valid                  ():                  grade                  .                  save                  ()                  return                  redirect                  (                  'home'                  )                  else                  :                  grade                  =                  DocumentForm                  ()                  return                  return                  (                  request                  ,                  'core/model_form_upload.html'                  ,                  {                  'form'                  :                  class                  })                              

model_form_upload.html

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

Near the FileField upload_to Parameter

See the example below:

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

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

It is also possible to practise something like:

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

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

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

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

Download the Examples

The code used in this post is bachelor on Github.

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


powelltoofte.blogspot.com

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

Postar um comentário for "Django Upload Document Html to Open an Upload Window"