I need to display multiple images linked to a single property, and am using two models to do this, one with a ForeignKey to the other. As a first step, I’m just including the models in admin.py to upload data there myself. I am able to upload the images fine.
No matter what I can’t manage to get this very simple behaviour to work, I’ve looked at multiple threads elsewhere but must be missing something fundamental. I’ve tried a lot of different ways to handle this, I’ll paste my most recent attempt below, thanks for any help.
models.py
class Property(models.Model):
"""Model representing a property."""
title = models.CharField(max_length=200)
id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text='Unique ID for this property')
summary = models.TextField(max_length=1000,
help_text='Enter a brief description of the property.')
guests = models.IntegerField(
default=1,
validators=[
MinValueValidator(1,message='There is a minimum one person per booking!'),
MaxValueValidator(10000,message='That is too many.')
]
)
description = models.TextField(max_length=1600, help_text='Enter a longer description of the property.')
location = models.ForeignKey(
Location,
null=True,
on_delete=models.SET_NULL
)
beds = models.IntegerField(
default=1,
validators=[
MinValueValidator(1,message='There is a minimum one bed per property!'),
MaxValueValidator(10000,message='That is too many.')
]
)
bathrooms = models.IntegerField(
default=1,
validators=[
MinValueValidator(1,message='There is a minimum one bathroom per property!'),
MaxValueValidator(10000,message='That is too many.')
]
)
host = models.TextField(max_length=80, help_text='Enter the name of the host')
def __str__(self):
"""String for representing the Model object."""
return f'{self.title}'
def get_absolute_url(self):
"""Returns the url to access a detail record for this book."""
return reverse('property-detail', args=[str(self.id)])
def grouped(l, n):
# Yield successive n-sized chunks from l.
for i in xrange(0, len(l), n):
yield l[i:i+n]
def get_image_filename(instance, filename):
title = instance.my_property.title
slug = slugify(title)
return "property_images/%s-%s" % (slug, filename)
class PropertyImages(models.Model):
"""Images for a model"""
my_property = models.ForeignKey(
Property,
null=True,
on_delete=models.SET_NULL,
related_name='images',
)
images = models.ImageField(
verbose_name='images',
upload_to=get_image_filename,
)
views.py
class PropertyListView(generic.ListView):
'''Generic view to query database and get all records for Property'''
model = Property
paginate_by = 10
urls.py
urlpatterns = [
path('properties/', views.PropertyListView.as_view(), name='properties'),
]
property_list.html (simplified just to display image from each property
{% for property in property_list.all %}
{{ property.title }}
<img src="{{ property.images.url }}">
{% endfor %}