3

I'm trying to get two inputs from a URL into a view by using regular expressions.

My urls.py line looks like this:

(r'^blog/(?P<match>.+)/', 'blog.views.blog'),

And this is my view:

def blog(request, match):
    pieces = match.split('/')

However, if my URL is "root.com/blog/user/3" pieces only returns [user].

In order for pieces to return [user],[3]`, a trailing slash has to be added to my URL: "root.com/blog/user/3/".

And as far as I know and according to my Python shell, the first URL should have returned [user],[3].

Am I missing something? Or does Django actually split strings differently from Python?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
bcoop713
  • 1,063
  • 5
  • 13
  • 24
  • do you want `user`, and `3` as 2 separate variables in the views? – karthikr May 30 '13 at 19:01
  • It seems to be not a very good idead, actually, to get arguments this way. Are you sure you _really_ want to do this? – kirelagin May 30 '13 at 19:02
  • @karthikr yes, i have user = pieces[0], and number = pieces[1], however, with the first url, i get an error because the pieces list is out of range. – bcoop713 May 30 '13 at 19:03
  • @kirelagin If there is another method that results in pretty URLs than I'm all ears. – bcoop713 May 30 '13 at 19:04
  • @bcoop713 I think it is an issue with regex. Just answered the question. See if that serves your purpose – karthikr May 30 '13 at 19:08
  • You should be having a separate view for users. The pattern will be `r'^blog/user/(?P\d+)$'`. Then you'll have another view for, say, posts with a pattern `r'^blog/post/(?P\d+)$'` and so on. – kirelagin May 30 '13 at 19:08
  • @kirelagin looks like the OP wants flexibility to send in key value pairs via url – karthikr May 30 '13 at 19:15
  • @karthikr looks like the OP hasn't given enough thought to his URL scheme and doesn't have much experience with Django, so I'm trying to help with that. – kirelagin May 30 '13 at 19:17
  • The canonical question is *[How can I split a URL string up into separate parts in Python?](https://stackoverflow.com/questions/449775/)* (2009). – Peter Mortensen Nov 28 '22 at 02:36

1 Answers1

3

The problem is that your regexp doesn't match the whole URL because the pattern ends with a slash, and your URL doesn't.

But since regexp without an explicit $ at the end matches a prefix of a string, if you'll have a look at your match variable you'll notice that it is user/, not user/3 as you might expect.

Update: (more verbose explanation)

r'^blog/.*/' matches [blog/user/] and [blog/user/]3 (square brackets used to denote actually matched parts).

If you try r'^blog/.*/$' you'll notice that blog/user/3 won't match at all since there is not slash at the end.

kirelagin
  • 13,248
  • 2
  • 42
  • 57
  • 2
    Just so everyone knows, I forgot the dollar sign, the solution is (r'^blog/(?P.+)/$', 'blog.views.blog'), and the above is the explanation of why it didn't work :) – bcoop713 May 30 '13 at 19:19