djangodjango-modelsdjango-viewsdjango-templatesdjango-file-upload

How to upload any type of file in Django?


I want to accept any type of file from the user and save it in the database. I am using following code:

In HTML file :

<input type="file" name="file_name" required>

But when I try to access the file in views.py it throws the Exception as 'file_name'.

file_name = request.FILES['file_name']

In the same field when I select some image. The image is stored in the media folder.

urls.py

urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

settings.py

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

views.py

try:
    file_name = request.FILES['file_name']        
except Exception as e:
    print('In Exception')
    print(e)

Exception shows after printing In Exception as:

Traceback (most recent call last):
  File "C:\Python310\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "C:\Python310\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\kambl\PycharmProjects\Linkingzz - 08 Mar\Linkingzz\Linkingzz\Linkingzz\app\views.py", line 534, in article
    file_name = request.FILES['articleName']
  File "C:\Python310\lib\site-packages\django\utils\datastructures.py", line 85, in __getitem__
    raise MultiValueDictKeyError(key)
django.utils.datastructures.MultiValueDictKeyError: 'articleName'

models.py

class Article(models.Model):
    FileField = models.FileField(upload_to='Order - Articel Files', blank=True, null=True)
    ImageField = models.ImageField(upload_to='Order - Featured Images', blank=True, null=True)
    

    def __str__(self):
        return str(self.id)

Solution

  • I have added "enctype="multipart/form-data" In form tag and it's working fine.

    <form method="POST" enctype="multipart/form-data">