首页 文章

Django Error u“'polls”不是注册的命名空间

提问于
浏览
42

昨天我正在使用本教程开发我的第一个应用程序 . 这是一个民意调查和选择应用程序 . 第一页显示问题,当您点击问题时,它会显示您可以对其进行投票的选项 .

昨天我有很棒的人帮我,并告诉我使用命名空间 . 我已经阅读了命名空间教程,并尝试将我的知识应用到场景中,但到目前为止它还没有工作 .

当我点击第一页的问题时,这是我的错误 .

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>
10 {% endfor %} 11 <input type="submit" value="Vote" /> 12 </form>

现在我知道问题隐藏在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)),
 )

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


)

我在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))

我的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>
{% endfor %} <input type="submit" value="Vote" /> </form>

11 回答

  • -3
    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>
    {% endfor %} <input type="submit" value="Vote" /> </form>
  • 6

    请仔细阅读官方Django文档,您将找到最合适的答案 .

    答案是将命名空间添加到根URLconf . 在mysite / urls.py文件(项目的urls.py,而不是应用程序的文件)中,继续并将其更改为包括命名空间:

    urlpatterns = patterns('',
    url(r'^polls/', include('polls.urls', namespace="polls")),
    url(r'^admin/', include(admin.site.urls)),
    )
    

    此外,在教程Namespacing URL names的第3部分中,提到使用app_name作为添加轮询命名空间的可接受方式 . 您可以在 polls/urls.py 中为此添加以下行:

    app_name = 'polls'
    urlpatterns = [
        ...
    ]
    
  • 117

    遵循相同的Django教程并具有相同的名称,我不得不在 mysite/urls.py 中更改:

    url(r'^polls/', include('polls.urls')),
    

    至:

    url(r'^polls/', include('polls.urls', namespace="polls")),
    
  • 1

    您需要将以下行添加到detail.html的顶部:

    {% load url from future %}
    

    (注意,您已经在index.html中使用了这一行,以便使用polls命名空间)

  • 17

    在myapp / urls.py中添加以下模块级属性:

    app_name = "polls"
    

    这将为该应用程序设置“应用程序命名空间名称” . 当你反过来使用像“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 =属性确实是正确的方法 .

  • 0

    我想你错过了命名空间:

    urlpatterns = patterns('',
        url(r'^polls/', include('polls.urls', namespace="polls")),
    )
    
  • 5

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

    urls.py

    from django.contrib import admin
    from django.urls import path, include
    
    
    urlpatterns = [
        path('admin/', admin.site.urls),
        path('yourapp/', include('yourapp.urls')),
        ]
    
  • 7

    更换行: {% url 'polls:vote' poll.id %} with: {% url 'vote' poll.id %} 为我解决了......

  • -2

    命名空间应该添加polls / urls.py文件 .

    url(r'^myapp/$', include('myapp.urls',  namespace ='myapp')),
    
  • 2

    问题出在教程中 . 在将命名空间(在您的情况下为'myapp')添加到URLconf时,本教程使用以下代码行:

    app_name = 'myapp'
    

    由于某种原因,Django框架将其视为unicode字符串 . 请将您的应用名称用双引号括起来,而不是单引号 . 例如,

    app_name = "myapp"
    

    这肯定会解决您的问题 . 我有同样的问题,这样做解决了它 .

  • 5

    重新启动Web服务器 . 只是 .

相关问题