I’m really new to Django. I’m having difficulty displaying images based on their name and according to the url pattern.
So basically the url consists of several variables within them and I want to be able to use that to fetch a particular image that is named with those variables.
Example:
localhost:8080/farm/chicken
this would fetch an image inside of my ../static/images/ folder and get:
farm_chicken.jpg
Another example:
localhost:8080/zoo/alligator
would get:
zoo_alligator.jpg
I can fetch the url parameters. So, should I make these image names within my views.py file and pass the names (zoo_alligator) into a context to be retrieved by the template later on? Would this be the correct way?
Thank you for your advice everybody! I appreciate all the help!
Sure, this is one way to do it. Something like this:
Then in
image_view:However, as your view is very simple – you can pass the path directly to the template from
urls.py, usingdirect_to_template:In
some_template.html:The problem is that you won’t get your string formatting done as the default filters do not have a “replace” function. You can easily write a custom filter:
Then modify the template:
You should read the documentation on writing custom filters and tags for more details including where to store the filter code to make sure django can find it.