[Answered ]-Slugs not appearing in URLS

1👍

Short answer
The url that is opening the page with the image is <a href="{% url 'viewimage' photo.id %}">, and since you are feeding in photo.id, that’s what you’re getting. You could change it to <a href="{% url 'viewimage' photo.slug %}"> and that should solve the problem.

But
But this will create problems since you are allowing null=True for the slug field, so what happens when you have a PostImage instance with no slug? An error, since your url is expecting a parameter, <slug:slug>:

path('viewimage/<slug:slug>/', views.viewImage, name='viewimage'),

I don’t see why you need to make the slug field null, since you have a save() function that will fill it in automatically, though it does have a typo, I believe, and that is slugify(self.title). What is self.title? Perhaps you meant self.image_title?:

class PostImage(models.Model):
    image = models.ImageField(null=False, blank=False, upload_to="images", default="default.png")
    image_title = models.CharField(max_length=100, null=False, blank=False, default="")
    slug = models.SlugField()

    def save(self, *args, **kwargs):
        self.slug = self.slug or slugify(self.image_title)
        super().save(*args, **kwargs)
    ...

Unfortunately
Unfortunately, there is still something that will go wrong in your views, since you are trying to get a photo = PostImage.objects.get(slug=slug), but now slug will be an actual slug, not an id. Easy to fix:

def viewImage(request, slug):
    photo = PostImage.objects.get(slug=slug)
    return render(request, 'viewimage.html', {'photo': photo, 'slug': slug})

And since you should never try to get an object without checking if it can be done first:

def viewImage(request, slug):
    try:
        photo = PostImage.objects.get(slug=slug)
    except PostImage.DoesNotExist:
        print("PostImage with this slug does not exist")
        photo = None
    return render(request, 'viewimage.html', {'photo': photo, 'slug': slug})

Leave a comment