I'm trying to append a parameter no_rep
at the end of my question url as a signal to show different views. I'm using Django 1.8 and following the url pattern from askbot.
This is the url.py :
url(
(r'^%s(?P<id>\d+)/' % QUESTION_PAGE_BASE_URL.strip('/') +
r'(%s)?' % r'/no-rep:(?P<no_rep>\w+)'),
views.readers.question,
name='question'
),
I'm trying to show different displays depending on the value of no_rep
in my url.
This is the view :
def question(request, id, no_rep):
if no_rep == '1':
request.session['no_rep'] = True
else:
request.session['no_rep'] = False
I couldn't find information on what the +,%,? do, which is probably where the problem is. Could someone explain how the regex work with the base url? When I enter the url http://localhost:8000/question6/test-question/no_rep:1
, request.session['no_rep']
should be set to true, but it's not. What am I missing?
Your url looks like this after all substitutions (%): r'^question(?P<id>\\d+)/(/no-rep:(?P<no_rep>\\w+))?'
, so:
1. Missing part for test-question
2. You have odd grouping around named group no_rep
(which is legal, but not recommended )
So for url like http://localhost:8000/question6/test-question/no_rep:1
your url pattern should look like this:
r'^%s(?P<id>\\d+)/test-question/(?:no_rep:(?P<no_rep>\\d+))?' % QUESTION_PAGE_BASE_URL.strip('/')
r'^%s(?P<id>\\d+)/test-question/(?:no_rep:(?P<no_rep>\\d+))?' % QUESTION_PAGE_BASE_URL.strip('/')
(you can change \\d+ in the last group for \\w+ if you want letters to match too).
About non-capturing groups (?:...)
and meaning of + and ? you can read in the documentation of Python re module.
Change your url patterns to something like this,
urlpatterns = [
url(r'question/(?P<id>\d+)/no-rep/(?P<no_rep>\w+)/', question),
]
OR
QUESTION_PAGE_BASE_URL = "question"
urlpatterns = [
url(r'{QUESTION_PAGE_BASE_URL}/(?P<id>\d+)/no-rep/(?P<no_rep>\w+)/'.format(
QUESTION_PAGE_BASE_URL=QUESTION_PAGE_BASE_URL), question),
] + router.urls
NOTE :
It's not good idea to use named groups
like id
along with some string or char like urls, ( localhost:8000/question6/
)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.