Search code examples
pythonjinja2webapp2

Pass variable from jinja2 template to python


Sorry if this is a noob question I am still learning. I have passed a variable from python code to a jinja2 HTML template to set up a URL, like this:

<a href="/delete/{{ result.key.id() }}">Delete</a>

When this link is pressed it should run a query that deletes the entity with that ID. But when the link is pressed it goes to /delete/1827424298 for example, which results in a 404 error as the request handler doesn't exist.

I need to pass that ID back into my python code so it can run a method to delete the entity with that same ID. How do I go about doing this? Using webapp2 if that is important.

class DeleteRequestHandler(webapp2.RequestHandler):

def get():


    template = template_env.get_template('myrequests.html')
    context = {

        'results': results.key.id()

    }

    self.response.out.write(template.render(context))

EDIT: I've added my delete handler - it is incomplete as I have yet to add the query to delete the entity. My thinking behind it so far is I can grab the results.key.id() from the jinja2 template and put it into results but I am not sure if this would work.


Solution

  • So I think what you're confused about is how to set up a route handler with a dynamic part to the URL. It's a shame that this is completely skipped over in the webapp2 tutorial, as it's a fundamental part of writing any web application. However, it is covered well in the guide to routing, which you should read.

    At its simplest, it's just a matter of putting a regex in the route:

    app = webapp2.WSGIApplication([
        ...
        (r'/delete/(\d+)', MyDeleteHandler),
    ])
    

    which will now route any URL of the form /delete/<number>/ to your deletion handler.

    The ID that you pass in the URL will be the first positional argument to the handler method:

    class MyDeleteHandler:
        def get(self, item_id):
            key = ndb.Key(MyModel, item_id)   # or whatever