2👍
✅
You can dynamically generate a url with all of the city names, but the url will be cached once django accesses it the first time, so in order to modify the url regex, you’d have to restart the django process. If that’s fine for your purposes, you can generate the url like this:
url(r'^projects/(?P<city>{})/$'.format(city_slugs.join('|')),
get_city, name='city-view')
But, it would probably be better to create a view routing method that implements the logic to send requests to their appropriate view:
# urls.py
# ...
url(r'^projects/(?P<slug>[-\w]+)/$',
project_city_router, name='project-city-router'),
# ...
# views.py
def is_a_city(slug):
# If they're in the database, something like:
# return City.objects.filter(slug=slug).exists()
return slug in ['london', 'paris', 'new-york', '...']
def project_city_router(request, slug=None):
if not slug:
# /projects/
return render(request, 'my/template.html', {'foo': 'bar'})
elif is_a_city(slug):
# /projects/<city>/
return get_city(request, city=slug)
else:
# /projects/<project-name/
return get_project(request, project_name=slug)
With this router, if the slug
argument is a project or city, it returns the result of the get_project
or get_city
view itself.
This also allows for your list of cities to be checked dynamically against a database, or file.
Source:stackexchange.com