简体   繁体   中英

Django/python images not displayed

I'm trying to show an image in Django, the problem is it won't show up when I add the HTML template, I have tried all combinations (ex: {{ cars.image_main.url }} , {{ car.image_main.url }} ).

If I delete all the HTML form Template and write {{ cars.image_main.url }} the image will show up. but When I put the HTML template back and insert the {{ cars.image_main.url }} into the code, the image does show up.

models.py:

class Car(models.Model):
    dealer = models.ForeignKey(Dealer, on_delete=models.DO_NOTHING)
    brand = models.CharField(max_length=100)
    CATEGORY = (
        ('New', 'New'),
        ('Used', 'Used')
    )
    category = models.CharField(max_length=50, choices=CATEGORY)
    image_main = models.ImageField(upload_to='images')
    image1 = models.ImageField(upload_to='images', blank=True)
    image2 = models.ImageField(upload_to='images', blank=True)
    image3 = models.ImageField(upload_to='images', blank=True)
    engine = models.CharField(max_length=100, blank=True)
    stock_number = models.IntegerField(blank=True, null=True)
    mpg = models.CharField(max_length=100, blank=True)
    exterior_color = models.CharField(max_length=100, blank=True)
    interior_color = models.CharField(max_length=100, blank=True)
    drivetrain = models.CharField(max_length=100, blank=True)
    mileage = models.IntegerField(blank=True, null=True)
    sold = models.BooleanField(default=False, blank=False)
    
    transmission = models.CharField(max_length=50, blank=True)
    YEAR_CHOICES = [(r, r) for r in range(2005, datetime.date.today().year+1)]
    year = models.IntegerField(
        ('year'), choices=YEAR_CHOICES, default=datetime.datetime.now().year)
    power = models.IntegerField()
    fuel = models.CharField(max_length=50, blank=True)
    price = models.IntegerField()
    description = models.TextField()
    date = models.DateField()
    
    def __str__(self):
        return self.brand
    
    def get_absolute_url(self):
        return reverse('car_detail', kwargs={
            'car_id': self.id
        })

views.py:

def car_detail(request, car_id):
    cars = get_object_or_404(Car, id=car_id)

    context = {
        'cars': cars
    }
    return render(request, 'car_detail.html', context)

car_detail.html:

    <li data-thumb="images/thumbnail1.jpg"> <a href="#"><img src="images/thumbnail1.jpg" alt="" /></a> </li>

Try this: car_detail.html:

<li data-thumb="images/thumbnail1.jpg"> <a href="#"><img src="{{ cars.image_main.url }}" alt="" /></a> </li>

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