Pergunta

I'm trying to build a small wiki, but I'm having problems writing the regex rules for them.

What I'm trying to do is that every page should have an edit page of its own, and when I press submit on the edit page, it should redirect me to the wiki page.

I want to have the following urls in my application:

  • http://example.com/<page_name>

  • http://example.com/_edit/<page_name>

My URLConf has the following rules:

url(r'(_edit/?P<page_name>(?:[a-zA-Z0-9_-]+/?)*)', views.edit),
url(r'(?P<page_name>(^(?:_edit?)?:[a-zA-Z0-9_-]+/?)*)', views.page),

But they're not working for some reason.

How can I make this work?

It seems that one - or both - match the same things.

Foi útil?

Solução

Following a more concise approach I'd really define the edit URL as:

http://example.com/<pagename>/edit

This is more clear and guessable in my humble opinion.

Then, remember that Django loops your url patterns, in the same order you defined them, and stops on the first one matching the incoming request. So the order they are defined with is really important.

Coming with the answer to your question:

^(?P<page_name>[\w]+)$ matches a request to any /PageName

Please always remember the starting caret and the final dollar signs, that are saying we expect the URL to start and stop respectively right before and after our regexp, otherwise any leading or trailing symbol/character would make the regexp match as well (while you likely want to show up a 404 in that case).

^_edit/(?P<page_name>[\w]+)$ matches the edit URL (or ^(?P<page_name>[\w]+)/edit$ if you like the user-friendly URL commonly referred to as REST urls, while RESTfullnes is a concept that has nothing to do with URL style).


Summarizing put the following in your urls:

url(r'^(?P<page_name>[\w]+)$', views.page)
url(r'^_edit/(?P<page_name>[\w]+)$', views.edit)

You can easily force URLs not to have some particular character by changing \w with a set defined by yourself.

To learn more about Django URL Dispatching read here.

Note: Regexp's are as powerful as dangerous, especially when coming on network. Keep it simple, and be sure to really understand what are you defining, otherwise your web application may be exposed to several security issues.

Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems. -- Jamie Zawinski

Outras dicas

Please try the following URLs, that are simpler:

url(r'_edit/(?P<page_name>[\w-]+), views.edit)'
url(r'(?P<page_name>[\w-]+), views.page),
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top