Samuel
Samuel

Reputation: 1406

Passing pattern to url

I want to map two or more seller to the same method ecommerce.views.seller. Below is the working code:

urlpatterns = patterns('',
    url(r'^(?:store1|store3)/$', 'ecommerce.views.seller'),
)

Is there any way by which I can declare some variable with pattern and simply pass it into urlpatterns. Something like:

SELLER_ID = '?:store1|store3'
urlpatterns = patterns('',
    url(r'^(SELLER_ID)/$', 'ecommerce.views.seller'),
)

Upvotes: 0

Views: 51

Answers (2)

Risadinha
Risadinha

Reputation: 16666

You should use capturing groups for regex path variables in order to have them provided as keyword arguments in your view method:

https://docs.djangoproject.com/en/1.10/topics/http/urls/#specifying-defaults-for-view-arguments

There is a very short example at the above link.

What you would probably want to do:

urlpatterns = patterns('',
    url(r'^store(?P<pk>[0-9]+)/$', 'ecommerce.views.seller'),
)

in ecommerce/views.py:

def seller(request, pk):
    seller = get_object_or_404(Store, pk=pk)  # if DB object
    # or if not in DB then just use the number
    # do your stuff
    return response

or use a generic view if the PK points to a DB model:

urlpatterns = patterns('',
    url(r'^store(?P<pk>[0-9]+)/$', StoreDetailView.as_view(), name='store_detail'),
)

class StoreDetailView(DetailView):
    model = Store
    # the rest is django magic, you just have to provide the template

Upvotes: 0

Ozgur Vatansever
Ozgur Vatansever

Reputation: 52093

Just use regular string formatting syntax:

url(r'^({})/$'.format(SELLER_ID), 'ecommerce.views.seller')

Upvotes: 2

Related Questions