2017-11-16 20 views
0

Djangoを初めて使用し、このエラーが発生しました。テンプレートが正しくレンダリングされました。私が行った唯一の変更は、views.pyファイルにブレークポイントをシミュレートするために '1/0'を追加することでした。そして、テンプレートを削除するとレンダリングされません。Djangoで逆引き一致エラーが発生しない

urls.py

from django.conf.urls import url 
from django.shortcuts import redirect 
from django.views.decorators.csrf import csrf_exempt 
from django.contrib.auth.views import login, logout 
from app.views import send_morsel, start_hunt, MorselList, MorselDetailView,\ 
register, create_morsel, HomePageView, FAQPageView, AboutPageView,\ 
newsletter_signup, edit_morsel 

app_name = 'app' 
urlpatterns = [ 
    url(r'^$', HomePageView.as_view(), name='home'), 
    url(r'^morsels/$', MorselList.as_view(), name='morsel_list'), 
    url(r'^morsels/send/$', send_morsel, name='morsel_send'), 
    url(r'^morsels/(?P<morsel_id>[0-9])/start_hunt/$', start_hunt, name='start_hunt'), 
    url(r'^register/', register, name='register'), 
    url(r'^faq/$', FAQPageView.as_view(), name='faq'), 
    url(r'^about/$', AboutPageView.as_view(), name='about'), 
    url(r'^morsels/create/$', create_morsel, name="create_morsel"), 
    url(r'^morsels/(?P<morsel_id>[0-9])/edit/$', edit_morsel, name='edit_morsel'), 
    url(r'^morsels/(?P<pk>[0-9])/display/$', MorselDetailView.as_view(), name='morsel_detail'), 
    url(r'^newsletter_signup/$', newsletter_signup, name='newsletter_signup') 
] 

morsel_list.html

{% extends "app/base.html" %} 
{% load bootstrap3 %} 
{% bootstrap_css %} 
{% bootstrap_javascript %} 
{% bootstrap_messages %} 
{% block content %} 
    <h2>Morsels</h2> 
    {% if user.is_authenticated %} 
     <p>hello</p> 
     <p>welcome {{ user.username }}</p> 
     <p><a href="/logout">Logout</a></p> 
    {% else %} 
     <p><a href="/login">Login</a></p> 
     <p><a href="/app/register">Register</a></p> 
    {% endif %} 
    <ul> 
     {% for morsel in object_list %} 
      <li>{{ morsel.name }} 
       <a href="{%url 'app:morsel_detail' morsel.id%}">View</a> 
       <a href="{%url 'app:edit_morsel' morsel.id %}">Edit</a> 
       <a href="{%url 'app:start_hunt' morsel.id%}">Send! </a> 
      </li> 
     {% endfor %} 
    </ul> 
    {% if messages %} 
     {% for msg in messages %}  
      {% bootstrap_alert msg.message alert_type=msg.level_tag %} 
     {% endfor %} 
    {% endif %} 
{% endblock %} 

ここに何をすべきか本当にわかりません。

views.pyから関連するブロック:

def edit_morsel(request, morsel_id=None): 
    if request.method == 'POST': 
     extra = int(request.session['extra']) 
     form = MorselCreationForm(request.POST) 
     formset = formset_factory(QuestionAnswerCreationForm, extra=extra)(request.POST) 
     if form.is_valid() and formset.is_valid(): 
      name = form.cleaned_data["name"] 
      start_time = form.cleaned_data["start_time"] 
      end_time = form.cleaned_data["end_time"] 
      welcome_text = form.cleaned_data["welcome_text"] 
      completed_text = form.cleaned_data["completed_text"] 
      public_enabled = form.cleaned_data["public_enabled"] 
      m = Morsel(
       name=name, 
       start_time = start_time, 
       end_time = end_time, 
       welcome_text = welcome_text, 
       completed_text = completed_text, 
       public_enabled = public_enabled 
      ) 
      m.save() 
      # this order is important to be able to access the relations 
      for form in formset: 
       question_text = form.cleaned_data["question_text"] 
       q = Question(
        question_text=question_text, 
        morsel = m 
       ) 
       answer = Answer(question=q) 
       q.answer.answer_text = form.cleaned_data["answer_text"] 
       q.save() 
    morsel = get_object_or_404(Morsel.objects.prefetch_related('questions'), pk=morsel_id) 
    form = MorselCreationForm(initial={ 
     "start_time" : morsel.start_time, 
     "end_time" : morsel.end_time, 
     "name" : morsel.name, 
     "welcome_text" : morsel.welcome_text, 
     "completed_text" : morsel.completed_text, 
     "public_enabled" : morsel.public_enabled 
    }) 
    initial_formset_values = [{"question_text":question.question_text,"answer_text":question.answer.answer_text} \ 
    for question in morsel.questions.select_related("answer").all()] 
    formset = formset_factory(QuestionAnswerCreationForm, extra=1, max_num=len(morsel.questions.all()))(initial=initial_formset_values) 
    return render(request, 'app/edit_morsel.html', {'form':form, 'formset':formset}) 

トレースバック:あなたのurls.pyで

Environment: 


Request Method: GET 
Request URL: http://localhost:8000/app/morsels/ 

Django Version: 1.11.6 
Python Version: 3.6.3 
Installed Applications: 
['django.contrib.admin', 
'django.contrib.auth', 
'django.contrib.contenttypes', 
'django.contrib.sessions', 
'django.contrib.messages', 
'django.contrib.staticfiles', 
'app.apps.AppConfig', 
'django_extensions', 
'twilio', 
'debug_toolbar', 
'bootstrap3', 
'sass_processor'] 
Installed Middleware: 
['django.middleware.security.SecurityMiddleware', 
'django.contrib.sessions.middleware.SessionMiddleware', 
'django.middleware.common.CommonMiddleware', 
'django.middleware.csrf.CsrfViewMiddleware', 
'django.contrib.auth.middleware.AuthenticationMiddleware', 
'django.contrib.messages.middleware.MessageMiddleware', 
'django.middleware.clickjacking.XFrameOptionsMiddleware', 
'debug_toolbar.middleware.DebugToolbarMiddleware'] 


Template error: 
In template /Users/kiniadit/code/morsels/app/templates/app/base.html, error at line 12 
    Reverse for 'morsel_detail' with arguments '(10,)' not found. 1 pattern(s) tried: ['app/morsels/(?P<pk>[0-9])/display/$'] 2 : <html><head> 
    3 :   <meta charset="utf-8"> 
    4 :   <meta name="viewport" content="width=device-width, initial-scale=1"> 
    5 :   <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" type="text/css">s 
    6 :   
    7 :   <!-- Custom links --> 
    8 :   <link href="{% static 'app/css/style.css' %}" rel="stylesheet" type="text/css" /> 
    9 :   <body> 
    10 :   <nav class="navbar navbar-expand-md navbar-dark bg-success"> 
    11 :   <div class="container"> 
    12 :    <a class="navbar-brand" href="/"><img sr c="{% static 'app/images/logo.png' %}"></a> 
    13 :    <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbar2SupportedContent" aria-controls="navbar2SupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> 
    14 :    <div class="collapse navbar-collapse text-center justify-content-end" id="navbar2SupportedContent"> 
    15 :    <ul class="navbar-nav"> 
    16 :     <li class="nav-item"> 
    17 :     <a class="nav-link text-white" href="{% url 'app:about' %}">About</a> 
    18 :     </li> 
    19 :     <li class="nav-item"> 
    20 :     <a class="nav-link text-white" href="{% url 'app:faq' %}">FAQ</a> 
    21 :     </li> 
    22 :    </ul> 


Traceback: 

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 
    41.    response = get_response(request) 

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 
    217.     response = self.process_exception_by_middleware(e, request) 

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 
    215.     response = response.render() 

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/template/response.py" in render 
    107.    self.content = self.rendered_content 

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/template/response.py" in rendered_content 
    84.   content = template.render(context, self._request) 

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/template/backends/django.py" in render 
    66.    return self.template.render(context) 

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/template/base.py" in render 
    207.      return self._render(context) 

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/test/utils.py" in instrumented_test_render 
    107.  return self.nodelist.render(context) 

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/template/base.py" in render 
    990.     bit = node.render_annotated(context) 

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/template/base.py" in render_annotated 
    957.    return self.render(context) 

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/template/loader_tags.py" in render 
    177.    return compiled_parent._render(context) 

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/test/utils.py" in instrumented_test_render 
    107.  return self.nodelist.render(context) 

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/template/base.py" in render 
    990.     bit = node.render_annotated(context) 

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/template/base.py" in render_annotated 
    957.    return self.render(context) 

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/template/loader_tags.py" in render 
    72.     result = block.nodelist.render(context) 

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/template/base.py" in render 
    990.     bit = node.render_annotated(context) 

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/template/base.py" in render_annotated 
    957.    return self.render(context) 

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/template/defaulttags.py" in render 
    216.      nodelist.append(node.render_annotated(context)) 

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/template/base.py" in render_annotated 
    957.    return self.render(context) 

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/template/defaulttags.py" in render 
    458.    url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app) 

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/urls/base.py" in reverse 
    91.  return force_text(iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))) 

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/urls/resolvers.py" in _reverse_with_prefix 
    497.   raise NoReverseMatch(msg) 

Exception Type: NoReverseMatch at /app/morsels/ 
Exception Value: Reverse for 'morsel_detail' with arguments '(10,)' not found. 1 pattern(s) tried: ['app/morsels/(?P<pk>[0-9])/display/$'] 
+0

あなたの 'base.html'の外観はどうですか?それは、それを修正した – Hybrid

答えて

1

正規表現が1桁に一致するため、pk=9では有効ですが、pk=10では正しく動作しません。 +を追加して、複数の数字に一致させます。

url(r'^morsels/(?P<pk>[0-9]+)/display/$', MorselDetailView.as_view(), name='morsel_detail'), 

あなたにも[0-9]を使用し、あなたの他のURLパターンを修正する必要があります。

+0

からのエラーの原因と思われます!ありがとうございました。 – user3588841

0

、あなたが持っている:URL(R '^一口/(P [0-9?を])/ display/$ '、MorselDetailView.as_view()、name =' morsel_detail ')、pk(プライマリキー)は、リクエスト時にパラメータpkに名前を付ける必要があることを意味します。エラーが示すように、あなたはmorsel_idと呼ばれるパラメータを送信しようとします。それはpkであると考えられます。したがって、エラーが発生します。morsel_list.htmlファイル内で、View to Viewを切り替えてください。

関連する問題