Momentum logo
Team 13 Classroom

๐Ÿป File Upload with Django and DRF ๐Ÿป

Posted on Jul 28th, 2022

๐Ÿ—“๏ธ Todayโ€™s Topics

  • How are the projects coming along? ๐Ÿ‘€
  • Letting users upload files/images using AWS S3

๐ŸŽฏ Project

Keep on going. ๐Ÿ’ช ๐Ÿš€

Today letโ€™s get you past any blockers you may be experiencing and talk through next steps.

By now you should have provided your front end with a way to log in and log out, and endpoints to see at least some data. You can create some data via the Django admin so that you can see your GET requests working. By tomorrow you should be able to create (at least some)resources via POST requests.

๐Ÿ“– Read | ๐Ÿ“บ Watch | ๐ŸŽง Listen

File Upload

On Monday weโ€™ll be covering full-text search in your API, but if you have time you can check these resources out in advance.

๐Ÿ”– Resources

File uploads

A request with a file attachment using Insomnia

  • Select the right HTTP method for your endpoint.
  • Choose binary file attachment from the JSON menu (where you normally put the body of a request)
  • Set headers on the Headers tab (this example assumes an image file in jpeg format, named profile-photo.jpg):

    Content-Type: image/jpeg
    Content-Disposition: attachment; filename=profile-photo.jpg
    

For more information on the values for Content-Type:

CORS for file upload

Assuming you are using django-cors-headers, youโ€™ll need to add the following to settings.py to allow the request headers necessary for file attachments:

# in settings.py

from corsheaders.defaults import default_headers

CORS_ALLOW_HEADERS = list(default_headers) + [
    'content-disposition',
]

Authentication

Make sure you are sharing the Djoser information with your front end. You should include the authentication endpoints in your API documentation or project README.

Creating a properly hashed password

In order to save a properly hashed password when you create a new user in the Django Admin, make sure you are using UserAdmin in admin.py so that you have that option in the admin interface. If you donโ€™t do this and save an unhashed password, you will run into authentication errors.

from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
...
admin.site.register(User, UserAdmin)

You can also change a password from the command line:

๐Ÿ‘พ Code

Back to home