简体   繁体   中英

Serving static images in the development environment

I'm getting this broken image when I try to serve it from the media root. Kindly requesting you..not to show me the links for the docs or to previous questions. I've tried those things but I'm still getting this broken image.

Models.py:

class BasicModel(models.Model):
    name = models.CharField(max_length=200)
    dob = models.DateField()
    photo = models.ImageField(upload_to='sample')

class BasicModelForm(ModelForm):
    class Meta:
            model = BasicModel

Views.py:

def BasicView(request):
    if request.method == 'POST':
            form = BasicModelForm(request.POST, request.FILES)
            if form.is_valid():
                    data = form.save()
                    return preview(request, data.id)
    else:
            form = BasicModelForm()
    return render_to_response("unnamed.html", {'form': form}, context_instance=RequestContext(request))

def preview(request, id):
    obj = get_object_or_404(BasicModel, pk=id)
    return render_to_response("preview.html", {'obj': obj})

Settings.py:

MEDIA_ROOT = '/home/nirmal/try/files/'
MEDIA_URL = 'http://localhost:8000/files/'

Urls.py:

url(r'^unnamed/$', 'unnamed.views.BasicView'),
url(r'^files/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),

Preview.html:

<html>
<body>
{{ obj.name }}
{{ obj.dob }}
<img src="{{ MEDIA_URL }}sample/{{ obj.photo }}" />
</body>
</html>

Could anyone help me on this?

Thanks!

Replace:

{{ MEDIA_URL }}sample/{{ obj.photo }}

With:

{{ object.photo.url }}

As a side note, are you sure that {{ MEDIA_URL }} is even defined in the template ?

I think to remember that the ImageField representation returns the URL relative to MEDIA_URL . Which means you should use the following code in your template:

<html>
<body>
{{ obj.name }}
{{ obj.dob }}
<img src="{{ MEDIA_URL }}{{ obj.photo }}" />
</body>
</html>

Or even shorter, use the absolute URL path with:

<html>
<body>
{{ obj.name }}
{{ obj.dob }}
<img src="{{ obj.photo.url }}" />
</body>
</html>

Hint, look up the URL of the broken image in your browser. I guess it is something like http://localhost:8000/files/sample/sample/xyz.png .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM