我正在使用Django 1.7上传图像并在模板上查看它们。出于某种原因,我上传的图像没有显示。我已经验证它们已上载并且路径已保存在数据库中。但是当从模板中检索它时,我什么也得不到。我有以下代码:
models.py
...
class Pet(models.Model):
title = models.CharField(_("Title"), max_length=120)
slug = models.SlugField(max_length=100, db_index=True)
description = models.TextField(_("Description"), default='')
....
class PetImage(models.Model):
pet = models.ForeignKey(Pet, related_name='images')
title = models.CharField(max_length=200, null=True, blank=True)
image = models.ImageField(upload_to="pet_images", null=True, blank=True)
forms.py
from django.forms.models import inlineformset_factory
from django.forms import ModelForm
from .models import Pet, PetImage
class PetForm(ModelForm):
class Meta:
model = Pet
fields = ('title', 'description',)
PetImageFormset = inlineformset_factory(Pet, PetImage, fields=('image',), can_delete=False, extra=3)
views.py
...
def new_pet(request):
form = PetForm()
img_formset = PetImageFormset(instance=Pet())
if request.method == 'POST':
form = PetForm(data=request.POST)
if form.is_valid():
pet = form.save(commit=True)
img_formset = PetImageFormset(request.POST, request.FILES, instance=pet)
if img_formset.is_valid():
img_formset.save()
return redirect(pet)
return render(request, "pets/new_pet.html", {
'form': form,
'img_formset': img_formset,
'action': "Create"
})
def view_pet(request, pet_slug, pet_id):
pet = get_object_or_404(Pet, pk=pet_id)
return render(request, 'pets/view_pet.html', {'pet': pet})
urls.py
from django.conf.urls import patterns, url
urlpatterns = patterns('',
url(r'^$', 'apps.pets.views.all_pets', name='all_pets'),
url(r'^(?P<pet_slug>[-\w\d]+),(?P<pet_id>\d+)/$', 'apps.pets.views.view_pet', name='view_pet'),
url(r'^new$', 'apps.pets.views.new_pet', name='new_pet'),
)
如何在模板上查看与宠物相关的图像?这是我到目前为止所尝试的但是没有显示图像:
view_pet.html
<ul class="slides">
{% for photo in pet.petimage_set.all %}
<li><img src="{{ MEDIA_URL }}{{ photo.image }}" /> </li>
{% endfor %}
</ul>
答案 0 :(得分:1)
由于PetImage
外键的related_name
模型Pet
为“图片”,因此请将循环更改为
{% for photo in pet.images.all %}