sup*_*ep1 47 django namespaces
昨天我正在使用本教程开发我的第一个应用程序.这是一个民意调查和选择应用程序.第一页显示问题,当您点击问题时,它会显示您可以对其进行投票的选项.
昨天我有很棒的人帮我,并告诉我使用命名空间.我已经阅读了命名空间教程,并尝试将我的知识应用到场景中,但到目前为止它还没有工作.
当我点击第一页的问题时,这是我的错误.
NoReverseMatch at /polls/5/
u"'polls" is not a registered namespace
Request Method: GET
Request URL: http://127.0.0.1:8000/polls/5/
Django Version: 1.4.3
Exception Type: NoReverseMatch
Exception Value:
u"'polls" is not a registered namespace
Exception Location: C:\hp\bin\Python\Lib\site-packages\django\template\defaulttags.py in render, line 424
Python Executable: C:\hp\bin\Python\python.exe
Python Version: 2.5.2
Python Path:
['C:\\djcode\\mysite',
'C:\\hp\\bin\\Python\\python25.zip',
'C:\\hp\\bin\\Python\\DLLs',
'C:\\hp\\bin\\Python\\lib',
'C:\\hp\\bin\\Python\\lib\\plat-win',
'C:\\hp\\bin\\Python\\lib\\lib-tk',
'C:\\hp\\bin\\Python',
'C:\\hp\\bin\\Python\\lib\\site-packages',
'C:\\hp\\bin\\Python\\lib\\site-packages\\win32',
'C:\\hp\\bin\\Python\\lib\\site-packages\\win32\\lib',
'C:\\hp\\bin\\Python\\lib\\site-packages\\Pythonwin']
Server time: Fri, 15 Feb 2013 21:04:10 +1100
Error during template rendering
In template C:\djcode\mysite\myapp\templates\myapp\detail.html, error at line 5
u"'polls" is not a registered namespace
1 <h1>{{ poll.question }}</h1>
2
3 {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
4
5 {% url 'polls:vote' poll.id %}
6 {% csrf_token %}
7 {% for choice in poll.choice_set.all %}
8 <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" />
9 <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br />
10 {% endfor %}
11 <input type="submit" value="Vote" />
12 </form>
Run Code Online (Sandbox Code Playgroud)
现在我知道问题隐藏在detail.html,我的主要网址和我的应用程序myapp URLCONF和views.py中
现在我的主URLconf是:C:\ djcode\mysite\mysite
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.conf import settings
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
#url(r'^polls/', include('myapp.urls')),
url(r'^polls/', include('myapp.urls', namespace='polls')),
url(r'^admin/', include(admin.site.urls)),
)
Run Code Online (Sandbox Code Playgroud)
我的app文件夹名为myapp,这是myapp URLconf:C:\ djcode\mysite\myapp
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.conf import settings
from django.conf.urls import patterns, include, url
urlpatterns = patterns('myapp.views',
url(r'^$', 'index'),
url(r'^(?P<poll_id>\d+)/$', 'detail'),
url(r'^(?P<poll_id>\d+)/results/$', 'results'),
url(r'^(?P<poll_id>\d+)/vote/$', 'vote'),
)
Run Code Online (Sandbox Code Playgroud)
我在myapp中的views.py是:
from django.http import HttpResponse
from myapp.models import Poll ,choice
from django.template import Context, loader
from django.http import Http404
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
def index(request):
latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
return render_to_response('myapp/index.html', {'latest_poll_list': latest_poll_list})
def results(request, poll_id):
p = get_object_or_404(Poll, pk=poll_id)
return render_to_response('myapp/results.html', {'poll': p})
def vote(request, poll_id):
p = get_object_or_404(Poll, pk=poll_id)
try:
selected_choice = p.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
# Redisplay the poll voting form.
return render_to_response('myapp/detail.html', {
'poll': p,
'error_message': "You didn't select a choice.",
}, context_instance=RequestContext(request))
else:
selected_choice.votes += 1
selected_choice.save()
# Always return an HttpResponseRedirect after successfully dealing
# with POST data. This prevents data from being posted twice if a
# user hits the Back button.
return HttpResponseRedirect(reverse('myapp.views.results', args=(p.id,)))
def detail(request, poll_id):
p = get_object_or_404(Poll, pk=poll_id)
return render_to_response('myapp/detail.html', {'poll': p},
context_instance=RequestContext(request))
Run Code Online (Sandbox Code Playgroud)
我的detail.html C:\ djcode\mysite\myapp\templates\myapp
<h1>{{ poll.question }}</h1>
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
{% url 'polls:vote' poll.id %}
{% csrf_token %}
{% for choice in poll.choice_set.all %}
<input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" />
<label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br />
{% endfor %}
<input type="submit" value="Vote" />
</form>
Run Code Online (Sandbox Code Playgroud)
JCh*_*___ 119
请仔细阅读官方Django文档,您将找到最合适的答案.
答案是将命名空间添加到根URLconf.在mysite/urls.py文件(项目的urls.py,而不是应用程序的文件)中,继续并将其更改为包括命名空间:
urlpatterns = patterns('',
url(r'^polls/', include('polls.urls', namespace="polls")),
url(r'^admin/', include(admin.site.urls)),
)
Run Code Online (Sandbox Code Playgroud)
此外,在教程命名空间URL名称的第3部分中,提到使用app_name作为添加轮询命名空间的可接受方式.您可以在此处添加polls/urls.py以下内容:
app_name = 'polls'
urlpatterns = [
...
]
Run Code Online (Sandbox Code Playgroud)
par*_*nos 17
遵循相同的Django教程并具有相同的名称,我不得不改变mysite/urls.py
:
url(r'^polls/', include('polls.urls')),
Run Code Online (Sandbox Code Playgroud)
至:
url(r'^polls/', include('polls.urls', namespace="polls")),
Run Code Online (Sandbox Code Playgroud)
小智 7
您需要将以下行添加到detail.html的顶部:
{% load url from future %}
Run Code Online (Sandbox Code Playgroud)
(注意,您已经在index.html中使用了这一行,以便使用polls命名空间)
在myapp/urls.py中添加以下模块级属性:
app_name = "polls"
Run Code Online (Sandbox Code Playgroud)
这将为该应用程序设置"应用程序命名空间名称".当您反向使用"polls:submit"这样的名称时,Django会查看两个位置:应用程序命名空间(如上所述)和实例命名空间(使用"url"函数中的namespace =参数设置).如果您的项目有多个应用程序实例,后者很重要,但通常它是您想要的前者.
我遇到了这个问题,并且在url()函数中将namespace =设置为某种方式似乎是错误的.
请参阅教程的以下条目:https://docs.djangoproject.com/en/1.9/intro/tutorial03/#namespacing-url-names
更新:此信息适用于Django 1.9.在1.9之前,为include添加namespace =属性确实是正确的方法.
小智 6
Django 2.0
在yourapp/urls.py中
from django.urls import path
from . import views
app_name = 'yourapp'
urlpatterns = [
path('homepage/', views.HomepageView.as_view(), name='homepage'),
]
Run Code Online (Sandbox Code Playgroud)
在urls.py中
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('yourapp/', include('yourapp.urls')),
]
Run Code Online (Sandbox Code Playgroud)
我想你错过了命名空间:
urlpatterns = patterns('',
url(r'^polls/', include('polls.urls', namespace="polls")),
)
Run Code Online (Sandbox Code Playgroud)
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.conf import settings
urlpatterns = patterns('myapp.views',
url(r'^$', 'index', name="index"),
url(r'^(?P<poll_id>\d+)/$', 'detail', name="detail"),
url(r'^(?P<poll_id>\d+)/results/$', 'results', name="results"),
url(r'^(?P<poll_id>\d+)/vote/$', 'vote', name="vote"),
)
----------------------------------
<h1>{{ poll.question }}</h1>
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
<form method="post" action="{% url myapp:vote poll.id %}">
{% csrf_token %}
{% for choice in poll.choice_set.all %}
<input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" />
<label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br />
{% endfor %}
<input type="submit" value="Vote" />
</form>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
76144 次 |
| 最近记录: |