msahin
msahin

Reputation: 1760

How to use request.path in Django View get_context_data?

I want to use last part of the url in get_context_data in the view.

For example: if I have /foo/bar I want to get /bar in a variable in the view.

def get_context_data(self, **kwargs):
    ctx = super().get_context_data(**kwargs)
    ctx["url"] = request.path.split('/')[:-1]
    return ctx

Upvotes: 1

Views: 605

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476493

You can access the request object with self.request. So you here can implement this with:

    def get_context_data(self, **kwargs):
        ctx = super().get_context_data(**kwargs)
        ctx['url'] = self.request.path.split('/')[:-1]
        return ctx

Note that by using [:-1] you construct a list of strings. So it will be ['', '/foo'] when you enter /foo/bar. Or [''] for /foo, or ['', '/foo', '/bar'] for /foo/bar/qux.

You might want to use .rsplit(..) here:

    def get_context_data(self, **kwargs):
        ctx = super().get_context_data(**kwargs)
        ctx['url'] = self.request.path.rsplit('/', 1)[0]
        return ctx

Upvotes: 1

Related Questions