[Fixed]-Django URL.py advanced usage. How to utilize an own functions in url.py?

1👍

You can’t do that from the urls, but you can do it via middleware or on a per-view basis (or a mixin you use in multiple views). Here’s an example with accessing url arguments from middleware which is exactly what you want.

It would go something like this:

class TownSessionMiddleware(object): 
    def process_view(self, request, view_func, view_args, view_kwargs)
        self.set_session_town(request, view_kwargs.get('townslug'))

    def set_session_town(self, request, slug):
        if slug:
            town = Town.objects.get(slug=slug)
            request.session["town"] = town.id
            request.session["town_name"]= town.name

Caching and alternative logic when there is no town slug in the url (think homepage) is up to you.

Leave a comment