3π
This setup is working for me, maybe it will help you. It is for latest version of Django. Many answers in OS are for older Django versions.
URLS:
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
#url
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Settings:
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
Template:
<img src="{{ foo.image.url }}"><br>
Model:
image = models.ImageField(upload_to = 'img/', default = 'img/None/no-img.jpg')
My foo model has an imagefield, when it is stored, I can retrieve the full url through item.image.url
based on the above setup.
0π
In urls.py, try: static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
- [Django]-Django: ValidationError using is_authenticated and logout when authenticating from an external source
- [Django]-Google application engine, maximum number of static files?
- [Django]-Django form object has no attribute issue
0π
The URLS seem to be causing the problem.
from django.conf import settings
from django.conf.urls.static import url, static
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^news/(?P<pk>[0-9]+)/$', views.detail, name='detail'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
The logic behind those URL patterns displays my homepage and individual news articles. Each news article has a url of /news/, followed by the article number, i.e. /news/1.
Each article uses my Photo model via a ForeignKey in the Article model. This allows a photo to be tied to a specific article.
However, in my template, the URL is a jumble of news and images:
http://localhost:8000/news/2/img/phones.png.
The news URL correctly finds the news item but not the image associated with the news item. The correct result would display the individual article along with its associated image. Do I need another URL?
0π
The Request object in Django has a method,
build_absolute_uri()
Using this method you can get absolute url of the image field.
So to get the absolute url, you can use two methods
First method: Getting absolute url in view while doing GET request.
from settings import MEDIA_URL
class ClassName(APIView):
def get(self, *args, **kwargs):
model = models.ModelName.objects.get(name='pran')
absolute_url = self.request.build_absolute_uri('/').strip("/") + MEDIA_URL + str(model.image_field_name)
return Response({'url': absolute_url}, 200)
Method 2: If you are doing POST request and you are using serializer then pass request as context object to it.
ser = serializers.MySerializerName(data=request.data}, context={'request': request})
- [Django]-Update queryset with dictionary values
- [Django]-How to import Django Settings to python standalone script
- [Django]-Django migration dependency order
- [Django]-How to only sync custom permissions with syncdb?