Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/282.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Django URL关键字_Python_Django_Url - Fatal编程技术网

Python Django URL关键字

Python Django URL关键字,python,django,url,Python,Django,Url,对于以下Django代码,我在向模板传递url关键字时遇到问题 views.py def index(request,username): return render(request,'myaccount.html') projectname文件夹中的url.py urlpatterns = patterns('', url(r'^myaccount/',include('myaccount.urls')), ) myaccount应用程序中的url.py urlpatter

对于以下Django代码,我在向模板传递url关键字时遇到问题

views.py

def index(request,username):
    return render(request,'myaccount.html')
projectname文件夹中的url.py

urlpatterns = patterns('',
    url(r'^myaccount/',include('myaccount.urls')),
)
myaccount应用程序中的url.py

urlpatterns = patterns('',
    url(r'^(?P<username>[a-zA-Z0-9]+)/$','myaccount.views.index',name='myaccount'),
)
但是当我传递关键字时,它会显示错误

myaccount.html

    {% url 'myaccount' username %}

NoReverseMatch at /myaccount/Jerry/
Reverse for 'myaccount' with arguments '('',)' and keyword arguments '{}' not found.
当我像这样传递变量username时,错误得到修复:

def index(request,username):
    return render(request,'myaccount.html',{'username':username})

但是,有没有更快的方法呢?

在您的正则表达式中,您正在捕获一个密钥/值对,其中密钥等于用户名。您需要在url标记中指定username='Jerry'

p意味着捕获以下内容并将其链接到名为username的关键字

{% url 'myaccount' username='Jerry' %}
因此,在您的情况下,如果不为反向查找提供关键字参数,它将查找不存在的正则表达式模式

编辑

这可能会解决您的“更快的方式”问题。您应该尝试使用基于类的视图。看

如果要使用url模式->

    url(r'^(?P<somenumber>\d+)/test/$', views.TestView.as_view(), name='testview')
在test.html模板中,您只需执行以下操作

{{ somenumber }}
提取传入参数的值

TemplateView的get_context_data(self,**kwargs)函数将自动更新模板的上下文,以包含url模式中找到的任何键/值对参数


实际上,您可以重写此函数并调用super来更新模板上下文中所需的任何自定义k/w参数。

我希望此过程自动完成。我应该通过执行
render(请求'.html',{'username':username}来传递变量username吗
then?或者还有其他更快的方法吗?您可以使用基于类的视图并使用用户名更新上下文**kwargs。如果您定义用户名变量,这将防止对用户名进行硬编码。Jerry,请查看CBV TemplateView的此链接。**kwargs合并传入的关键字/单词参数。您可以使用这些参数进行upd为模板创建上下文。@Jerry,如果您在许多不同的模板中使用用户名,我认为您可以编写一个简单的两行上下文处理器。另一种可能是将用户名存储在会话中,并让CBV从LoginSessionMixin继承,后者使用会话数据(如用户名和其他凭据)更新上下文。您愿意吗你详细说明你所说的“更快的方式”是什么意思?这是经过身份验证的内容还是用户名?PaulRenton这是关于在任何包含
?P
的url中获得一个名为“用户名”的变量。它不需要登录。好的,如果我修改的答案是你想要的,请告诉我
from django.views.generic import TemplateView
class TestView(TemplateView):
    model = xxxx // link to your model here
    template_name = 'test.html'
{{ somenumber }}