Can You Upload an Audio File to Django Without a Forms.py

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


How to Upload Files With Django

How to Upload Files With Django

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

In this tutorial you lot will learn the concepts behind Django file upload and how to handle file upload using model forms. In the end of this post you lot volition discover the source code of the examples I used and so you can 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 upwardly placed in asking.FILES.

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

The course must be submitted using the POST method.

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

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

FileField and ImageField are created as a string field in the database (usually VARCHAR), containing the reference to the bodily file.

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

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

Each value in request.FILES is an UploadedFile instance.

You will need to set MEDIA_URL and MEDIA_ROOT in your project'due south settings.py.

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

In the evolution server y'all 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.


Simple File Upload

Post-obit is a minimal file upload instance using FileSystemStorage. Use it just to learn nearly the menstruation of the process.

simple_upload.html

                {% extends 'base.html' %}  {% load static %}  {% block content %}                  <form                  method=                  "post"                  enctype=                  "multipart/form-data"                  >                  {% csrf_token %}                  <input                  type=                  "file"                  proper noun=                  "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                  render                  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                  =                  request                  .                  FILES                  [                  'myfile'                  ]                  fs                  =                  FileSystemStorage                  ()                  filename                  =                  fs                  .                  save                  (                  myfile                  .                  proper noun                  ,                  myfile                  )                  uploaded_file_url                  =                  fs                  .                  url                  (                  filename                  )                  return                  render                  (                  request                  ,                  'cadre/simple_upload.html'                  ,                  {                  'uploaded_file_url'                  :                  uploaded_file_url                  })                  return                  render                  (                  asking                  ,                  'core/simple_upload.html'                  )                              

File Upload With Model Forms

Now, this is a way more than convenient way. 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                  class                  Document                  (                  models                  .                  Model                  ):                  description                  =                  models                  .                  CharField                  (                  max_length                  =                  255                  ,                  bare                  =                  True                  )                  document                  =                  models                  .                  FileField                  (                  upload_to                  =                  'documents/'                  )                  uploaded_at                  =                  models                  .                  DateTimeField                  (                  auto_now_add                  =                  Truthful                  )                              

forms.py

                                  from                  django                  import                  forms                  from                  uploads.core.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'                  :                  form                  =                  DocumentForm                  (                  request                  .                  Postal service                  ,                  request                  .                  FILES                  )                  if                  form                  .                  is_valid                  ():                  grade                  .                  save                  ()                  return                  redirect                  (                  'home'                  )                  else                  :                  grade                  =                  DocumentForm                  ()                  return                  return                  (                  asking                  ,                  '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</button>                  </form>                  <p><a                  href=                  "{% url 'domicile' %}"                  >Return to abode</a></p>                  {% endblock %}              

Nearly the FileField upload_to Parameter

See the instance beneath:

                                  document                  =                  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/                  %                  chiliad/                  %                  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 cord. This callable accepts 2 parameters, case and filename.

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

Download the Examples

The code used in this mail is bachelor on Github.

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


clarkwhade1965.blogspot.com

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

0 Response to "Can You Upload an Audio File to Django Without a Forms.py"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel