Django1.8' app'不是注册的命名空间

时间:2016-08-05 13:47:21

标签: python django

我的错误:

    <h1>{{ question.question_text }}</h1>
    {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}

    <form action="{% url 'app:vote' question.id %}" method="post">
    {% csrf_token %}
    {% for choice in question.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>

我想知道为什么这里错了。 这是该文件的官方网站写的

detail.html

<h1>{{ question.question_text }}</h1>

{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}

<form action="{% url 'app:vote' question.id %}" method="post">
{% csrf_token %}
{% for choice in question.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>

现在我知道问题出在detail.html,我的主要网址和我的应用名为myapp URLCONF和views.py

views.py

def vote(request, question_id):
    p = get_object_or_404(Question, pk=question_id)
    try:
        selected_choice = p.choice_set.get(pk=request.POST['choice'])
    except (KeyError, Choice.DoesNotExist):
        # Redisplay the question voting form.
        return render(request, 'polls/detail.html', {
            'question': p,
            'error_message': "You didn't select a choice.",
        })
    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('polls:results', args=(p.id,)))

我的urls.py

urlpatterns = [
    url(r'^$',views.Index,name='index'),
    url(r'^(?P<question_id>\d+)/$',views.detail,name='detail'),
    url(r'^(?P<question_id>\d+)/results/$', views.results, name='results'),
    url(r'^(?P<question_id>\d+)/vote/$', views.vote, name='vote'),
    url(r'^admin/', admin.site.urls),
]

2 个答案:

答案 0 :(得分:0)

当您在根urls.py中包含其他网址配置时,会使用命名空间。本教程中的示例有效,因为他们有include('polls.urls') in tutorial 1,然后in tutorial 3他们在app_name = 'polls'中设置了polls/urls.py,并将网址标记更改为{{1} }}

在您的情况下,您的所有网址格式都在根配置中,因此您应该从网址标记中删除命名空间。

{% 'polls:vote' question.id %}

答案 1 :(得分:0)

My Project picture

我添加了一个新的urls.py

此代码,mydjango / urls.py

from django.conf.urls import url,include
from django.contrib import admin

urlpatterns = [
    url(r'^app/', include('app.urls')),
    url(r'^admin/', admin.site.urls),
]

应用程序/ urls.py

from django.conf.urls import url

from . import views

urlpatterns = [
    url(r'^$', views.index, name='index'),
]