Ошибка NoReverseMatch: реверс для «эпизодешоуссылки» с аргументами «()» и аргументами ключевого слова «{}» не найден

По какой-то причине, которую я еще не понял, я получаю следующую ошибку:

Environment:


Request Method: GET
Request URL: http://192.168.33.10:8000/podfunnel/episodechaptermarks/54/

Django Version: 1.9
Python Version: 2.7.6
Installed Applications:
('producer',
 'django.contrib.admin',
 'django.contrib.sites',
 'registration',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'storages',
 'django_extensions',
 'randomslugfield',
 'adminsortable2',
 'crispy_forms')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware',
 'django.middleware.security.SecurityMiddleware')



Traceback:

File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
  149.                     response = self.process_exception_by_middleware(e, request)

File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
  147.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/decorators.py" in _wrapped_view
  23.                 return view_func(request, *args, **kwargs)

File "/home/vagrant/fullcast_project/producer/views/pod_funnel.py" in episodechaptermarks
  803.     return render(request, 'pod_funnel/forms_chapter_marks.html', context)

File "/usr/local/lib/python2.7/dist-packages/django/shortcuts.py" in render
  67.             template_name, context, request=request, using=using)

File "/usr/local/lib/python2.7/dist-packages/django/template/loader.py" in render_to_string
  97.         return template.render(context, request)

File "/usr/local/lib/python2.7/dist-packages/django/template/backends/django.py" in render
  95.             return self.template.render(context)

File "/usr/local/lib/python2.7/dist-packages/django/template/base.py" in render
  206.                     return self._render(context)

File "/usr/local/lib/python2.7/dist-packages/django/template/base.py" in _render
  197.         return self.nodelist.render(context)

File "/usr/local/lib/python2.7/dist-packages/django/template/base.py" in render
  988.                 bit = node.render_annotated(context)

File "/usr/local/lib/python2.7/dist-packages/django/template/base.py" in render_annotated
  955.             return self.render(context)

File "/usr/local/lib/python2.7/dist-packages/django/template/loader_tags.py" in render
  173.         return compiled_parent._render(context)

File "/usr/local/lib/python2.7/dist-packages/django/template/base.py" in _render
  197.         return self.nodelist.render(context)

File "/usr/local/lib/python2.7/dist-packages/django/template/base.py" in render
  988.                 bit = node.render_annotated(context)

File "/usr/local/lib/python2.7/dist-packages/django/template/base.py" in render_annotated
  955.             return self.render(context)

File "/usr/local/lib/python2.7/dist-packages/django/template/loader_tags.py" in render
  69.                 result = block.nodelist.render(context)

File "/usr/local/lib/python2.7/dist-packages/django/template/base.py" in render
  988.                 bit = node.render_annotated(context)

File "/usr/local/lib/python2.7/dist-packages/django/template/base.py" in render_annotated
  955.             return self.render(context)

File "/usr/local/lib/python2.7/dist-packages/django/template/defaulttags.py" in render
  513.                         six.reraise(*exc_info)

File "/usr/local/lib/python2.7/dist-packages/django/template/defaulttags.py" in render
  499.             url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app)

File "/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py" in reverse
  600.     return force_text(iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)))

File "/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py" in _reverse_with_prefix
  508.                              (lookup_view_s, args, kwargs, len(patterns), patterns))

Exception Type: NoReverseMatch at /podfunnel/episodechaptermarks/54/
Exception Value: Reverse for 'episodeshowlinks' with arguments '()' and keyword arguments '{}' not found. 1 pattern(s) tried: [u'podfunnel/episodeshowlinks/(?P<production_id>[0-9]+)/$']

Теперь все работало нормально. Поля ввода работали нормально и размещались в базе данных. Перенаправление на другой шаблон работало хорошо до сегодняшнего дня. Похоже, проблема в моем шаблоне form_chapter_marks.html под <a class="btn btn-primary box-shadow--6dp" href="{% url 'podfunnel:episodeshowlinks' %}" role="button"><i class="fa fa-chevron-right pull-right" aria-hidden="true"></i>&nbsp Next</a>, но я не знаю, почему ошибка отображается сейчас, когда у меня не было проблем с ней раньше.

Был бы признателен за помощь здесь.

Вот мои url шаблоны:

from django.conf.urls import url
from django.views.generic import TemplateView

import producer.views.pod_funnel as views

urlpatterns = [
    url(r'^dashboard/', views.dashboard, name="dashboard"),
    url(r'^clientsetup/', views.ClientSetupView.as_view(), name="clientsetup"),
    url(r'^podcastsetup/', views.PodcastSetupView.as_view(), name="podcastsetup"),
    url(r'^episodeinfo/$', views.EpisodeInfoView.as_view(), name="episodeinfo"),
    url(r'^episodeinfo/(?P<production_id>[0-9]+)/$', views.EpisodeInfoView.as_view(), name="episodeinfo_edit"),
    url(r'^episodeimagefiles/(?P<production_id>[0-9]+)/$', views.EpisodeImageFilesView.as_view(), name="episodeimagefiles"),
    url(r'^episodewordpressinfo/(?P<production_id>[0-9]+)/$', views.EpisodeWordpressInfoView.as_view(), name="episodewordpressinfo"),
    url(r'^episodechaptermarks/(?P<production_id>[0-9]+)/$', views.episodechaptermarks, name="episodechaptermarks"),
    url(r'^episodechaptermarks/(?P<chaptermark_id>[0-9]+)/$', views.episodechaptermarks, name="episodechaptermarks_edit"),
    url(r'^episodeshowlinks/(?P<production_id>[0-9]+)/$', views.episodeshowlinks, name="episodeshowlinks"),
    url(r'^episodeshowlinks/(?P<showlink_id>[0-9]+)/$', views.episodeshowlinks, name="episodeshowlinks_edit"),
    url(r'^episodetweetables/(?P<production_id>[0-9]+)/$', views.episodetweetables, name="episodetweetables"),
    url(r'^episodetweetables/(?P<tweetable_id>[0-9]+)/$', views.episodetweetables, name="episodetweetables_edit"),
    url(r'^episodeclicktotweet/(?P<production_id>[0-9]+)/$', views.episodeclicktotweet, name="episodeclicktotweet"),
    url(r'^episodeclicktotweet/(?P<clicktotweet_id>[0-9]+)/$', views.episodeclicktotweet, name="episodeclicktotweet_edit"),
    url(r'^episodeschedule/(?P<production_id>[0-9]+)/$', views.EpisodeScheduleView.as_view(), name="episodeschedule"),
    url(r'^accounts/', views.AccountsView.as_view(), name="accounts"),
    url(r'^wordpressaccount/', views.WordpressAccountView.as_view(), name="wordpressaccount"),
    url(r'^wordpressaccountsetup/', views.WordpressAccountSetupView.as_view(), name="wordpressaccountsetup"),
    url(r'^wordpressaccountsortable/', views.WordpressAccountSortableView.as_view(), name="wordpressaccountsortable"),
    url(r'^soundcloudaccount/', views.SoundcloudAccountView.as_view(), name="soundcloudaccount"),
    url(r'^soundcloud_auth/', views.SoundcloudAuthenticationView.as_view(), name="soundcloud_auth"),
    url(r'^twitteraccount/', views.TwitterAccountView.as_view(), name="twitteraccount"),
    url(r'^twitter_auth/', views.TwitterAuthenticationView.as_view(), name="twitter_auth"),
]

chaptermarks и episodeshowlinks посмотреть в pod_funnel.py

@login_required
def episodechaptermarks(request, *args, **kwargs):

    initial_values = {}
    user = request.user
    # production_id = request.production_id

    # Lets get client and podcast for the user already. if not existent raise 404
    client, podcast = get_podfunnel_client_and_podcast_for_user(user)
    if client is None or podcast is None:
        raise Http404

    # The production_id or the chaptermark_id must be passed on the kwargs
    production_id = kwargs.get('production_id', None)
    chaptermark_id = kwargs.get('chaptermark_id', None)
    if chaptermark_id is not None:
        chaptermark = get_object_or_404(ChapterMark, id=chaptermark_id)
        production = chaptermark.production
    # else:
    #     chaptermark_id = ChapterMark(id=chaptermark_id)
    elif production_id:
        production = get_object_or_404(Production, id=production_id)
        chaptermark = None

    initial_values['production_id'] = production.id

    if chaptermark is not None:
        initial_values['chaptermark_id'] = chaptermark_id
        initial_values['start_time'] = chaptermark.start_time
        initial_values['title'] = chaptermark.title

    # Create the formset, specifying the form and formset we want to use.
    EpisodeChapterMarksFormSet = formset_factory(EpisodeChapterMarksForm, formset=BaseChapterMarkFormSet)

    # Get our existing chapter mark data for this user.  This is used as initial data.
    chapter_marks = ChapterMark.objects.filter(id=chaptermark_id).order_by('start_time')
    chaptermarks_data = [{'start_time': c.start_time, 'title': c.title}
                    for c in chapter_marks]

    if request.method == 'POST':
        # chaptermarks_form = EpisodeChapterMarksForm(request.POST)
        chaptermarks_formset = EpisodeChapterMarksFormSet(request.POST)

        if chaptermarks_formset.is_valid():

            new_chaptermarks = []

            for chaptermarks_form in chaptermarks_formset:
                production_id = chaptermarks_form.cleaned_data.get('production_id')
                chaptermark_id = chaptermarks_form.cleaned_data.get('chaptermark_id')
                start_time = chaptermarks_form.cleaned_data.get('start_time')
                title = chaptermarks_form.cleaned_data.get('title')

                if chaptermark_id is not None:
                    chaptermark = ChapterMark.objects.get(id=chaptermark_id)
                else:
                    chaptermark = ChapterMark()

                if start_time and title:
                    new_chaptermarks.append(ChapterMark(id=chaptermark_id, start_time=start_time, title=title))

                chaptermark.start_time = start_time
                chaptermark.title = title
                chaptermark.production = production
                chaptermark.save()

    else:
        chapter_marks = ChapterMark(id=chaptermark_id)
        chaptermarks_formset = EpisodeChapterMarksFormSet(initial=chaptermarks_data)

    context = {
        'chapter_marks': chapter_marks,
        'chaptermarks_formset': chaptermarks_formset,
    }

    return render(request, 'pod_funnel/forms_chapter_marks.html', context)

---------------------

@login_required
def episodeshowlinks(request, *args, **kwargs):

    initial_values = {}
    user = request.user
    # production_id = request.production_id

    # Lets get client and podcast for the user already. if not existent raise 404
    client, podcast = get_podfunnel_client_and_podcast_for_user(user)
    if client is None or podcast is None:
        raise Http404

    # The production_id or the showlink_id must be passed on the kwargs
    production_id = kwargs.get('production_id', None)
    showlink_id = kwargs.get('showlink_id', None)
    if showlink_id is not None:
        showlink = get_object_or_404(ProductionLink, id=showlink_id)
        production = showlink.production
    # else:
    #     chaptermark_id = ChapterMark(id=chaptermark_id)
    elif production_id:
        production = get_object_or_404(Production, id=production_id)
        showlink = None

    initial_values['production_id'] = production.id

    if showlink is not None:
        initial_values['showlink_id'] = showlink_id
        initial_values['title'] = showlink.title
        initial_values['url'] = showlink.url

    # Create the formset, specifying the form and formset we want to use.
    EpisodeShowLinksFormSet = formset_factory(EpisodeShowLinksForm, formset=BaseShowLinkFormSet)

    # Get our existing chapter mark data for this user.  This is used as initial data.
    show_links = ProductionLink.objects.filter(id=showlink_id).order_by('title')
    showlinks_data = [{'title': s.title, 'url': s.url}
                         for s in show_links]

    if request.method == 'POST':
        # chaptermarks_form = EpisodeChapterMarksForm(request.POST)
        showlinks_formset = EpisodeShowLinksFormSet(request.POST)

        if showlinks_formset.is_valid():

            new_showlinks = []

            for showlinks_form in showlinks_formset:
                production_id = showlinks_form.cleaned_data.get('production_id')
                showlink_id = showlinks_form.cleaned_data.get('showlink_id')
                title = showlinks_form.cleaned_data.get('title')
                url = showlinks_form.cleaned_data.get('url')

                if showlink_id is not None:
                    showlink = ProductionLink.objects.get(id=showlink_id)
                else:
                    showlink = ProductionLink()

                if title and url:
                    new_showlinks.append(ProductionLink(id=showlink_id, title=title, url=url))

                showlink.title = title
                showlink.url = url
                showlink.production = production
                showlink.save()

    else:
        show_links = ProductionLink(id=showlink_id)
        showlinks_formset = EpisodeShowLinksFormSet(initial=showlinks_data)

    context = {
        'show_links': show_links,
        'showlinks_formset': showlinks_formset,
    }

    return render(request, 'pod_funnel/forms_show_links.html', context)

Шаблоны для chaptermarks и showlinks:

{% extends "pod_funnel/base.html" %}
{% load crispy_forms_tags %}

{% block content %}

<div class="progress">
  <div class="progress-bar progress-bar-striped progress-bar-success active" role="progressbar" aria-valuenow="50" aria-valuemin="0" aria-valuemax="100" style="width: 50%">
    <span class="sr-only">50% Complete</span>
  </div>
</div>

<div class="panel panel-default box-shadow--16dp col-sm-6 col-sm-offset-3">
<div class="panel-body">

<div class='row'>
<div class='col-sm-12'>

<h3>Chapter Marks</h3>

<hr/>

<form method='POST'>
    {% csrf_token %}

{{ chaptermarks_formset.management_form }}

    {% for chaptermarks_form in chaptermarks_formset %}
        <div class="chaptermarks-formset">
            {{ chaptermarks_form.start_time }}

            {{ chaptermarks_form.title }}

        </div>
    {% endfor %}

<hr/>

<button type="submit" class="btn btn-info btn-sm box-shadow--6dp">Save</button>
<p>
<p>
<a class="btn btn-primary box-shadow--6dp" href="{% url 'podfunnel:episodeshowlinks' %}" role="button"><i class="fa fa-chevron-right pull-right" aria-hidden="true"></i>&nbsp Next</a>

</form>

</div>
</div>

</div>
</div>

{% endblock %}

---------------

{% extends "pod_funnel/base.html" %}
{% load crispy_forms_tags %}

{% block content %}

<div class="progress">
  <div class="progress-bar progress-bar-striped progress-bar-success active" role="progressbar" aria-valuenow="62.5" aria-valuemin="0" aria-valuemax="100" style="width: 62.5%">
    <span class="sr-only">62.5% Complete</span>
  </div>
</div>

<div class="panel panel-default box-shadow--16dp col-sm-6 col-sm-offset-3">
<div class="panel-body">

<div class='row'>
<div class='col-sm-12'>

<h3>Show Links</h3>

<hr/>

<form method='POST'>
    {% csrf_token %}

{{ showlinks_formset.management_form }}

    {% for showlinks_form in showlinks_formset %}
        <div class="showlinks-formset">
            {{ showlinks_form.title }}

            {{ showlinks_form.url }}

        </div>
    {% endfor %}

<hr/>

<button type="submit" class="btn btn-info btn-sm box-shadow--6dp">Save</button>
<p>
<p>
<a class="btn btn-primary box-shadow--6dp" href="{% url 'podfunnel:episodetweetables' %}" role="button"><i class="fa fa-chevron-right pull-right" aria-hidden="true"></i>&nbsp Next</a>

</form>
</div>
</div>

</div>
</div>

{% endblock %}

person w_lpz    schedule 08.07.2016    source источник


Ответы (1)


Я не уверен, почему вы показали весь остальной код; достаточно URL-адресов и фрагмента шаблона.

В цитируемом фрагменте вы показываете, что звоните {% url 'podfunnel:episodeshowlinks' %}. Но ваши URL-адреса и сообщение об ошибке показывают, что единственный шаблон с именем episodeshowlinks ожидает аргумент: production_id. Вам нужно передать это в тег url, чтобы он знал, какой URL генерировать.

Обратите внимание, что обычно ваши URL-адреса кажутся очень неправильными; Я не могу понять, почему у вас есть, например, два URL-адреса с префиксом «episodeshowlinks/», один из которых принимает значение production_id, а другой — show_id, а второй — с именем «episodeshowlinks_edit». Django не может различать их, поэтому Django всегда будет вызывать первый, и вы никогда не получите "showlink_id" в kwargs.

person Daniel Roseman    schedule 08.07.2016
comment
Спасибо за ответ. Я добавил production_id следующим образом: href="{% url 'podfunnel:episodeshowlinks' production_id %}" и все еще получаю точную ошибку. Вместо того, чтобы получить аргумент '()', теперь я получаю '('',)'. Я также пробовал как production.id и безуспешно. - person w_lpz; 09.07.2016
comment
Ну, вы не отправляете ни production_id, ни production в контекст шаблона из представления, поэтому они пусты. - person Daniel Roseman; 09.07.2016