2đź‘Ť
Preface: First off, let’s clarify the direction in which things are mapped. You’re not assigning URLs to objects in your database; requests can be for any URL, and then Django has to figure out what that means, and how to reply.
i.e. it’s {url} -> looks up object
, not {object} -> has a URL
Here’s your URL route:
url(r'^(?P<question_id>[0-9]+)/$', 'papers.views.detail', name='detail'),
And here’s where you’re handling it:
def detail(request, question_id):
question = Question.objects.get(pk=question_id)
So what happens is when someone types in localhost:8000/34/
for example, it matches the regex rule “base URL followed by numbers”. If you want to change that to “base URL followed by a name”, you can do so:
url(r'^(?P<question_name>[\w_-]+)/$', 'papers.views.detail', name='detail'),
(Specifically here, letters, or the hyphen or underscore character; modify the regex according to what your “question name” looks like.)
You’ll then need to deal with the fact that your handler has to accept names:
def detail(request, question_name):
question = Question.objects.get(naslov=question_name)
The limitation here is that the .get
query has to result in a unique result; if it’s at all possible for multiple questions to have the same name, you’ll have trouble.
1đź‘Ť
You need to first change the URL pattern for papers.view.detail
so it doesn’t just match integers — something like \w+
instead of [0-9]+
. You probably want to rename the capturing group, too. See https://docs.python.org/2/library/re.html.
Then, you need to change the detail
method take an argument corresponding to the capturing group’s name, and to query for the object by that argument (which I guess is the naslov
field?).