django如何在url中获取TemplateView [英] django how to Dynamic get TemplateView in url

查看:124
本文介绍了django如何在url中获取TemplateView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下网址

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'),

和视图视图

class View1(TemplateView):
    pass

class View2(TemplateView):
    pass

class View3(TemplateView):
    pass

和我的问题是如何根据正则表达式动态获取TemplateView

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

ie,我想要一些像
url(r'^ view /(number)$',View (number).as_view(),name ='view'),

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

推荐答案

django文档是非常好的。请在提出问题之前搜索。这是Django Book的一个链接。 https://docs.djangoproject.com/ en / dev / ref / forms / validation /#form-and-field-validation

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.

所以 url(r'^ view /(\d +)$',view)

然后你的视图必须要有一个参数。

And then your view must take a parameter.

某些东西:

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

当然,更合乎逻辑的方式来使用这样的东西,将是数字对应一些数据(比如说,存储在数据库中的对象的pk)。记住,最好让你的网址意味着什么。所以如果有三个网址正在做一些完全不同的网址,也许他们应该看起来几乎相同,只有一个数字来区分它们。

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.

这篇关于django如何在url中获取TemplateView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆