Reputation: 11615
Why can't I display my uploaded images correctly using the following settings.
The url is showing correctly (I think) when viewing the page source. The image is just the broken image thumbnail image. The url in the source is shown as /media/uploads/group_images/my_image_name
If relevant, the image was uploaded from admin, but I also want to be able to upload elsewhere (ie - upload form in the rendered template)
in settings.py
....
MEDIA_URL = "/media/"
MEDIAFILES_DIRS = []
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
in models.py
class BlogGroup(models.Model):
title = BleachField()
image = models.ImageField(upload_to="uploads/group_images", default="uploads/group_images/none/none.jpg")
created = models.DateTimeField(default = datetime.now)
def __str__(self):
return self.title
in forms.py
class BlogGroupForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(BlogGroupForm, self).__init__(*args, **kwargs)
self.fields["title"].requried = True
self.fields["image"].required = True
self.fields["title"].widget = forms.TextInput()
class Meta:
model = BlogGroup
fields = ["title", "image"]
urls.py
urlpatterns = patterns('blog.views',
(r'^admin/', include(admin.site.urls)),
.....,
(r'^ckeditor/', include('ckeditor.urls')),
(r"", "main"),
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
view
def main(request):
groups = BlogGroup.objects.all().order_by("created")
context = {'groups':groups, 'user':request.user}
return render(request, "list.html", context)
template
{% for group in groups %}
<div class = "row">
<div class = "col-xs-12">
{{ group.title }}
</div>
<div class = "col-xs-12">
<img src = "{{ group.image.url }}" alt = ""/>
</div>
</div>
{% endfor %}
Upvotes: 0
Views: 345
Reputation: 2087
The problem is in your url dispatcher. When django proceeding url to dispatcher, it goes from top to bottom throw your urls, one by one, and stops if there is regexp match.
Your url ""
in (r"", "main"),
matches ALL strings.
You need to replace it to (r"^$", "main"),
to match just empty strings.
More info:
Upvotes: 2
Reputation: 759
change you url.py like this:
urlpatterns = patterns('blog.views',
(r'^admin/', include(admin.site.urls)),
.....,
(r'^ckeditor/', include('ckeditor.urls')),
(r"", "main"),
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Upvotes: 0