I am trying to store images on my backend that I can reference with an ImageField in able to link Users with a headshot. I haven't had any luck with documentation on how to do this in TastyPie.
What are the minimum viable steps I need to take to get an image from my backend displaying on an html webpage?
Here is my code of what I have been trying at:
models.py
from django.db import models
class User(models.Model):
name = models.CharField(max_length=100)
headshot = models.ImageField()
settings.py
MEDIA_URL = '/media/'
api.py
from tastypie.resources import ModelResource
from tastypie import fields
from blog.models import User
class UserResource(ModelResource):
headshot = fields.FileField(attribute='headshot', null=True, blank=True)
class Meta:
queryset = User.objects.all()
resource_name = 'users'
urls.py
from django.conf.urls import include, url
from django.contrib import admin
from tastypie.api import Api
from blog.api import UserResource
blog = Api(api_name='v1')
blog.register(UserResource())
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^blog/', include(blog.urls))
]
test image location--> /myproject/media/images/nickbrady.jpg
I created my user object like this:
User.objects.create(name='Nick Brady', headshot='images/nickbrady.jpg')
and my current API response is this:
{
"meta": {
"limit": 20,
"next": null,
"offset": 0,
"previous": null,
"total_count": 1
},
"objects": [
{
"headshot": "/media/images/nickbrady.jpg",
"id": 1,
"img": null,
"name": "Nick Brady",
"resource_uri": "/blog/v1/users/1/"
}
]
}
When I try to go to
http://127.0.0.1:8000/media/images/nickbrady.jpg
or many other combinations adding blog/v1/media, etc. I am not able to see the image through a browser or html page.
Does anyone know what I'm missing? I've had a really hard time finding documentation on how to do this in tastypie
This could be your problem:
User.objects.create(name='Nick Brady', headshot='images/nickbrady.jpg')
Unless that file is already in that location within your storage, it won't actually reference your file.
You probably want to wrap a file object in this class and save that instead of a string: https://docs.djangoproject.com/en/1.9/ref/files/file/
On save that file will get copied to your storage directory.