Adopt a Pet Help part 16(ish) - simple hyperlink problem? bug?

Please help! One small issue with the project, which I enjoyed. I cannot for the life of me figure out what is wrong with my hyperlink for one of the last steps. When I manually type in the path (like ~~ https://localhost/animals/dogs/0 ~~), I get what I want. I don’t understand why this hyperlink is different than the previous code I wrote. The picture is the code that must have something wrong with it, or there is a bug.

@app.route('/animals/<pet_type>')
def animals(pet_type):
  html = f'''<h1>List of {pet_type}</h1>'''
  
  for pet_idx, pet in enumerate(pets[pet_type.lower()]):
    html = html + '<li><a href="/animals/<pet_type>/<int:pet_idx>">' + pet['name'] + '</a></li>'
    
  return html
      
@app.route("/animals/<pet_type>/<int:pet_idx>")
def pet(pet_type, pet_idx):
  pet = pets[pet_type.lower()][pet_idx]
  #petname = pet['name']
  return f'''
  <h1>{pet['name']}</h1>
  <img src={pet['url']} </img>
  <p>{pet['description']} </p>
  <ul>
    <li>{pet['age']}</li>
    <li>{pet['breed']}</li>
  </ul>
  '''

I actually found the solution but cannot quite understand why this works. Can the hyperlink/href not inherit the objects defined in the function?

Working code with f strings:

  for pet_idx, pet in enumerate(pets[pet_type.lower()]):
    html = html + f'<li><a href="/animals/{pet_type}/{pet_idx}">' + pet['name'] + '</a></li>'

sucky code:

  for pet_idx, pet in enumerate(pets[pet_type.lower()]):
    html = html + '<li><a href="/animals/<pet_type>/<int:pet_idx>">' + pet['name'] + '</a></li>'

I suppose I can’t inherit objects using the <obj_blah> notation, like I can with f strings?

Yea that’s the difference. I suspect it has to do with how the @ decorator treats <pet_type> notation. I’m guessing it takes a string and parses that notation, whereas simply pasting that string into the url has no effect. I’d like to confirm this though at some point.

For more info: http://exploreflask.com/en/latest/views.html#url-converters

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.