简体   繁体   中英

What does this regex mean in django?

I'm learning django from a book and I've got into advanced urls, in here there is a regex that it's not explained:

urlpatterns = [
    url(r'^(?P<page_slug>\w+)-(?P<page_id>\w+)/',
        include([
        url(r'^history/$', views.history),
        url(r'^edit/$', views.edit),
        url(r'^discuss/$', views.discuss),
        url(r'^permissions/$', views.permissions),
    ])),
]

I understand that it's about removing redundancy, but how does it actually work? Where do you get page_slug and page_id from and what's with the - between them?

If you are moving onto advanced urls I presume you understand how the basic url markup works. The regex patterns are used whenever we are dealing with variable url patterns for eg In case of a blog, urls might read as

  • domain.com/post-1/
  • domain.com/post-2/

or

  • domain.com/shortpost-1/
  • domain.com/shortpost-2/

and so on.

We can see a common pattern here which can be related to as a page slug( or prefix) and page/post id. So we create two variables namely page_slug and page_id. (Note: The variable names like anywhere else can be renamed to your liking. The regex is hence created as /(?P<page_slug>\\w+)-(?P<page_id>\\w+))/' where:

  • ?P<> : defines that we are defining a variable
  • < text > : text is your variable's name
  • \\w+ : is your regex which defines what pattern is acceptable (In this case \\w represents anything in the set [0-9a-zA-Z_] and + represents any number of repititions . If you want to learn more on this I'll refer https://www.ntu.edu.sg/home/ehchua/programming/howto/Regexe.html for reference and http://regexr.com/ for practise.
  • and the - in between is simply a compulsary text which could have been replaced with say -no- to look like domain.com/page-no-1/

The rest of the markup is similar to normal urls which means that any url begining in the given pattern (?P<page_slug>\\w+)-(?P<page_id>\\w+)/ followed by the suffix is handeled by the mentioned view.

eg - domain.com/post-1/history/ - is handeled by views.history and so on.

The important part now is how do these variable names affect your views. If you are using function based views, your history view will be defined as :

def history(request, page_slug, page_id):
        #Your code using the two variables received.
        #These might be values stored in db to dynamically fetch values

In class based views to access the url parameters you use self.args or self.kwargs so you would access it by doing self.kwargs['page_slug']

This regex matches the following urls:

/abc-def/history/ (abc goes to page_slug and def to page_id)
/ghi-jkl/edit/

etc

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM