Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Rest Framework Uploaded File Url

Django rest framework automatically generates urls for uploaded files. However, the url it automatically generates doesn't actually point to where the file is stored. For example, I upload a file to my api named example.txt and this is what the object in my database looks like after the upload:

{
    name: "John Doe",
    bio: "localhost:8000/api/users/static/example.txt"
}

My static directory is located in the root directory so the file actually lives and can be accessed at localhost:8000/static/example.txt. The automatically generated url returns a 404. How can I overwrite the automatically generated url to be the correct one?

Here's what my model looks like:

class User(models.Model):
   name = models.CharField(primary_key=True, max_length=30)
   bio = models.FileField(null=True, blank=True, upload_to='static')

Here's what the serializer looks like:

class UserSerializer(serializers.ModelSerializer):
   class Meta:
     model = User
     fields = ("name", "bio")
like image 982
zjwhi Avatar asked Apr 08 '26 12:04

zjwhi


1 Answers

Define your MEDIA_URL and your MEDIA_ROOT into you settings.py

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

And add to your urls.py

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

MEDIA_ROOT is the absolute path where your file gonna be saved. And MEDIA_URL is the url that handles the media served from MEDIA_ROOT. And I should change upload_at=static to upload_to=bio/files, just because static path is for just static files as .css, .js and image files.

like image 106
Matheus Veleci Avatar answered Apr 11 '26 04:04

Matheus Veleci



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!