user4199417
user4199417

Reputation:

how is it possible to create URLs according to model entries in django

I have two fields source and destination in model cities

my application is named uroute. if user inputs some details like: source >paris, destination > bruxelles

then url needs to be generated like this: uroute/paristobruxelles

i have tried like this:

in urls.py

urlpatterns = [
    url(r'^(?P<source>+'to'+<destination>[A-Z][a-z]+)/$', views.detail, name='detail'),
]

in views.py

def detail(request, source, destination):
    return HttpResponse(source+'to'+'destination')

i have no idea what to do with views.py to be frank i am very naive to django. i request somebody to guide through. thanks in advance!

Upvotes: 1

Views: 46

Answers (1)

Aleksander S
Aleksander S

Reputation: 384

As Wtower pointed out in the comments, the approach you propose has a lot of edge cases you might encounter, like cities containing to in the name etc.

A more sustainable approach would be to maybe have something like uroute/paris/to/berlin if you wish to keep the to semantic of the URL.

Then it would allow you to easily capture the two cities in the following url pattern:

urlpatterns = [
    url(r'^(?P<source>[a-zA-Z]+)/to/(?P<destination>[a-zA-Z]+)/$', views.detail, name='detail'),
]

def detail(request, source, destination):
    """
    Do something
    """

Upvotes: 4

Related Questions