Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have the following urls

url(r'^view/1$', View1.as_view(), name='view'),
url(r'^view/2$', View2.as_view(), name='view'),
url(r'^view/3$', View3.as_view(), name='view'),

and the views views

class View1(TemplateView):
    pass

class View2(TemplateView):
    pass

class View3(TemplateView):
    pass

and my question is how to Dynamically get TemplateView based on a regular expression

i.e., I want something like url(r'^view/(number)$', View(number).as_view(), name='view'),

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
233 views
Welcome To Ask or Share your Answers For Others

1 Answer

The django documentation is quite good. Please search there before asking a question. Here's a link from the Django Book. https://docs.djangoproject.com/en/dev/ref/forms/validation/#form-and-field-validation

What you want is a regular expression for digits.

So url(r'^view/(d+)$', view)

And then your view must take a parameter.

Something like:

def view(request, number):
    if number == 1:
        #do first thing
    elif number == 2:
        #do second thing
    #etc...

Of course, the more logical way to use something like this, would be for the number to correspond to some data (say, the pk of an object stored in your database). Remember, it's best to have your urls mean something. So if there are three urls that are doing something totally different, maybe they should look almost identical, with only a number to differentiate them.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...