动态更改urls.py以支持动态创建的URL?

时间:2015-03-10 05:14:43

标签: django

我想使用Django创建一个Web服务,动态地将URL添加到我的urls.py文件中。这可以在Django中完成吗?换句话说,我希望用户能够注册使用Django动态创建的终点,例如:我的域名“dynamicurl.com”可以通过注册用户johnp添加/ johnp /。我该怎么做?

2 个答案:

答案 0 :(得分:4)

只需创建一个与用户名所需字符匹配的模式即可。这是一个例子:

url(r'(?P<username>[\w.@+-]+)/$',
    'yourapp.views.user_home', name='user-home'),

然后,当有人在您的视图中转到yourdomain.com/johnp/时,您可以执行以下操作:

def user_home(request, username=None):
    return render(request, 'user_home.html', {'username': username})

user_home.html

<strong>Welcome {{ username }}</strong>

这将导致:

欢迎johnp

答案 1 :(得分:1)

考虑这种情况。

假设在某个时间点您有一百万用户,您的urls.py文件将只有一百万条用户页面记录。我希望您不希望有单独的视图来处理所有这些单独的URL。

因此,最好定义url模式,这些模式可以根据url中收到的值动态更改模板内的内容。

使用基于类的视图,可以按如下方式完成:

在你的urls.py文件中,写下

url(r'^(?P<user_name>(.*))/$',ProfileView.as_view(),name='profile-view'),

class ProfileView(TemplateView):

    template_name = "abc.html"

    def get_context_data(self,**kwargs):
        context = super(ProfileView,self).get_context_data(**kwargs)
        context['user_name'] = kwargs['user_name']
        return context

然后,在您的模板中,您可以将其用作{{user_name}}

相关问题