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

Categories

0 votes
227 views
in Technique[技术] by (71.8m points)

regex - django how to Dynamic get TemplateView in url

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

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

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...