0

Our site has a main entity - city. Firstly a user selects a city from dropDownList (site stores it in session) and then uses the site's apps through /CITY/APP_NAME, for ex. www.mysite.com**/kyiv/**petitions/add.

I want to catch a city slug from an url and store it to a session. To do this, I have url.py like below:

    url(r'(?P<townslug>[a-z]+)/',include(urls_modules)),

and url_modules.py

    urlpatterns = [
    url(r'^$', views.index, name="index"),
    url(r'^edata/', include('edata.urls', namespace="edata")),
    url(r'^crowdfunding/', include('crowdfunding.urls')),
    url(r'^petitions/', include('petitions.urls', namespace="petitions")),
    url(r'^budget/', views.budget, name="budget"),
    url(r'^partners', views.partners),
]

My question is - how to cache city slug and put it into session directly from url_modules.py like:

     request.session["town"] = Town.objects.get(slug=townslug).id
     request.session["town_name"]= Town.objects.get(slug=townslug).name
Riko
  • 131
  • 2
  • 11
  • It's not clear what you're asking. Why do you want it in the session? And need importantly why do you want to do that in the urls? That's something you would do in the view. – Daniel Roseman May 01 '16 at 22:07

1 Answers1

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.

Anonymous
  • 11,740
  • 3
  • 40
  • 50