每个页面都有效,但索引页面上没有反向匹配

时间:2019-05-22 19:56:05

标签: python django

每个相关页面都有效,但只有索引页面可以获取

NoReverseMatch位于/ 找不到带有关键字参数'{'slug':''}'的'series_detail'。尝试了1个模式:['(?P [^ /] +)\ / $']

我真的不明白。每个页面的URL,包括series_detail的作品。...

问题是这一行: {{all_episode.series}}

这是我的代码(任何帮助将不胜感激)

urlpatterns = [
    path('admin/', admin.site.urls),

    path('', views.index, name='home'),
    path('<slug>/', views.series_pg, name='series_detail'),

    path('series/<slug>/', views.season_pg, name='season_detail'),
    path('series/season/<slug>', views.episode_pg, name='episode_detail'),

    path('about/',
        TemplateView.as_view(template_name='about.html'), name='about'),
]


if settings.DEBUG:
    urlpatterns += [
        re_path(r'^media/(?P<path>.*)$', serve, {
            'document_root': settings.MEDIA_ROOT,
        }),
    ]



def index(request):
    series = Series.objects.all()
    episode = Episode.objects.all().order_by("date")

    content_dict = {
        'series':series,
        'episode':episode,

    }

    return render(request, 'index.html', content_dict)

def series_pg(request, slug):
    series = Series.objects.get(slug=slug)
    season = Season.objects.filter(series=series).order_by("season_nr")
    episode = Episode.objects.filter(series=series).order_by("date")
    content_dict = {

        'series':series,
        'season':season,
        'episode':episode,
    }

    return render(request, 'series.html', content_dict)



def get_image_path_series(instance, filename):
    return '/'.join([''])

class Series(models.Model):
    name = models.CharField(max_length=128, unique=True)
    genre = models.CharField(max_length=128, default=1)
    tv_or_movie = models.CharField(max_length=128, default=1)
    period = models.CharField(max_length=128, default=1)
    descritpion = models.TextField()
    slug = models.SlugField(unique=True)
    image = models.ImageField(upload_to='get_image_path_series', blank=True, null=True)
    video = EmbedVideoField(blank=True, null=True)  

    def __str__(self):
        return self.name

编辑:index.html的模板+页面的回溯+终端的回溯

{% block content %}
<center>
    {% for tv_series in series %}
<div class="btn-group" role="group" aria-label="Basic example">
  <button type="button" class="btn btn-outline-primary">
 <a href="{% url 'series_detail' slug=tv_series.slug %} "onMouseOver="this.style.color='#0F0'"onMouseOut="this.style.color='#00F'" style="text-decoration:none">
{{ tv_series.name }}
</a></button>
</div>
{% endfor %}
</center>
<hr>

<center>
<br>
<div class="row">
  <div class="col-6 col-md-4">
        <div class="card">
        {% for all_episode in episode %}
        <a href="{% url 'episode_detail' slug=all_episode.slug %}"><img class="card-img-top" src='{{all_episode.image.url}}'></a>
            <div class="card-body">
                <h5 class="card-title"><a href="{% url 'episode_detail' slug=all_episode.slug %}">{{ all_episode.title }}</a></h5>
                <p class="card-text">{{ all_episode.story |slice:":100" }}...</p>
            </div>
<div class="card-footer">
                <small class="text-muted"><span class="h5"><a href="{% url 'series_detail' slug=all_episode.series.slug %}">{{ all_episode.series }}</a></span> / 
            <span class="h6"><a href="{% url 'season_detail' slug=all_episode.season.slug %}">{{ all_episode.season }}</a></span></small>
            </div>
        {% endfor %}




    </div>
  </div>

</div>
</center>



{% endblock content %}



Edit: Full Traceback

Environment:


Request Method: GET
Request URL: http://127.0.0.1:8000/

Django Version: 2.2.1
Python Version: 3.6.7
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'blog',
 'embed_video']
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']


Template error:
In template /mnt/c/Users/young/Desktop/project/myapp/blog/templates/base.html, error at line 0
   Reverse for 'series_detail' with keyword arguments '{'slug': ''}' not found. 1 pattern(s) tried: ['(?P<slug>[^/]+)\\/$']
   1 : {% load static %}
   2 : <!doctype html>
   3 : <html>
   4 : <head>
   5 :     <!-- Required meta tags -->
   6 :     <meta charset="utf-8">
   7 :     <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
   8 :     <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
   9 :     <link rel="stylesheet" href="{% static 'css/style.css' %}" />
   10 :     <style type="text/css">   


    Traceback:

    File "/mnt/c/Users/young/Desktop/project/myapp/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
      34.             response = get_response(request)

    File "/mnt/c/Users/young/Desktop/project/myapp/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
      115.                 response = self.process_exception_by_middleware(e, request)

    File "/mnt/c/Users/young/Desktop/project/myapp/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
      113.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

    File "/mnt/c/Users/young/Desktop/project/myapp/blog/views.py" in index
      17.   return render(request, 'index.html', content_dict)

    File "/mnt/c/Users/young/Desktop/project/myapp/lib/python3.6/site-packages/django/shortcuts.py" in render
      36.     content = loader.render_to_string(template_name, context, request, using=using)

    File "/mnt/c/Users/young/Desktop/project/myapp/lib/python3.6/site-packages/django/template/loader.py" in render_to_string
      62.     return template.render(context, request)

    File "/mnt/c/Users/young/Desktop/project/myapp/lib/python3.6/site-packages/django/template/backends/django.py" in render
      61.             return self.template.render(context)

    File "/mnt/c/Users/young/Desktop/project/myapp/lib/python3.6/site-packages/django/template/base.py" in render
      171.                     return self._render(context)

    File "/mnt/c/Users/young/Desktop/project/myapp/lib/python3.6/site-packages/django/template/base.py" in _render
      163.         return self.nodelist.render(context)

    File "/mnt/c/Users/young/Desktop/project/myapp/lib/python3.6/site-packages/django/template/base.py" in render
      937.                 bit = node.render_annotated(context)

    File "/mnt/c/Users/young/Desktop/project/myapp/lib/python3.6/site-packages/django/template/base.py" in render_annotated
      904.             return self.render(context)

    File "/mnt/c/Users/young/Desktop/project/myapp/lib/python3.6/site-packages/django/template/loader_tags.py" in render
      150.             return compiled_parent._render(context)

    File "/mnt/c/Users/young/Desktop/project/myapp/lib/python3.6/site-packages/django/template/base.py" in _render
      163.         return self.nodelist.render(context)

    File "/mnt/c/Users/young/Desktop/project/myapp/lib/python3.6/site-packages/django/template/base.py" in render
      937.                 bit = node.render_annotated(context)

    File "/mnt/c/Users/young/Desktop/project/myapp/lib/python3.6/site-packages/django/template/base.py" in render_annotated
      904.             return self.render(context)

    File "/mnt/c/Users/young/Desktop/project/myapp/lib/python3.6/site-packages/django/template/loader_tags.py" in render
      62.                 result = block.nodelist.render(context)

    File "/mnt/c/Users/young/Desktop/project/myapp/lib/python3.6/site-packages/django/template/base.py" in render
      937.                 bit = node.render_annotated(context)

    File "/mnt/c/Users/young/Desktop/project/myapp/lib/python3.6/site-packages/django/template/base.py" in render_annotated
      904.             return self.render(context)

    File "/mnt/c/Users/young/Desktop/project/myapp/lib/python3.6/site-packages/django/template/defaulttags.py" in render
      209.                     nodelist.append(node.render_annotated(context))

    File "/mnt/c/Users/young/Desktop/project/myapp/lib/python3.6/site-packages/django/template/base.py" in render_annotated
      904.             return self.render(context)

    File "/mnt/c/Users/young/Desktop/project/myapp/lib/python3.6/site-packages/django/template/defaulttags.py" in render
      443.             url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app)

    File "/mnt/c/Users/young/Desktop/project/myapp/lib/python3.6/site-packages/django/urls/base.py" in reverse
      90.     return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))

    File "/mnt/c/Users/young/Desktop/project/myapp/lib/python3.6/site-packages/django/urls/resolvers.py" in _reverse_with_prefix
      668.         raise NoReverseMatch(msg)

    Exception Type: NoReverseMatch at /
    Exception Value: Reverse for 'series_detail' with keyword arguments '{'slug': ''}' not found. 1 pattern(s) tried: ['(?P<slug>[^/]+)\\/$']



    Edit: From terminal I get 
    python manage.py runserver
    Watching for file changes with StatReloader
    Performing system checks...

    System check identified no issues (0 silenced).
    May 22, 2019 - 20:03:01
    Django version 2.2.1, using settings 'myapp.settings'
    Starting development server at http://127.0.0.1:8000/
    Quit the server with CONTROL-C.
    Internal Server Error: /
    Traceback (most recent call last):
      File "/mnt/c/Users/young/Desktop/project/myapp/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
        response = get_response(request)
      File "/mnt/c/Users/young/Desktop/project/myapp/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response
        response = self.process_exception_by_middleware(e, request)
      File "/mnt/c/Users/young/Desktop/project/myapp/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response
        response = wrapped_callback(request, *callback_args, **callback_kwargs)
      File "/mnt/c/Users/young/Desktop/project/myapp/blog/views.py", line 17, in index
        return render(request, 'index.html', content_dict)
      File "/mnt/c/Users/young/Desktop/project/myapp/lib/python3.6/site-packages/django/shortcuts.py", line 36, in render
        content = loader.render_to_string(template_name, context, request, using=using)
      File "/mnt/c/Users/young/Desktop/project/myapp/lib/python3.6/site-packages/django/template/loader.py", line 62, in render_to_string
        return template.render(context, request)
      File "/mnt/c/Users/young/Desktop/project/myapp/lib/python3.6/site-packages/django/template/backends/django.py", line 61, in render
        return self.template.render(context)
      File "/mnt/c/Users/young/Desktop/project/myapp/lib/python3.6/site-packages/django/template/base.py", line 171, in render
        return self._render(context)
      File "/mnt/c/Users/young/Desktop/project/myapp/lib/python3.6/site-packages/django/template/base.py", line 163, in _render
        return self.nodelist.render(context)
      File "/mnt/c/Users/young/Desktop/project/myapp/lib/python3.6/site-packages/django/template/base.py", line 937, in render
        bit = node.render_annotated(context)
      File "/mnt/c/Users/young/Desktop/project/myapp/lib/python3.6/site-packages/django/template/base.py", line 904, in render_annotated
        return self.render(context)
      File "/mnt/c/Users/young/Desktop/project/myapp/lib/python3.6/site-packages/django/template/loader_tags.py", line 150, in render
        return compiled_parent._render(context)
      File "/mnt/c/Users/young/Desktop/project/myapp/lib/python3.6/site-packages/django/template/base.py", line 163, in _render
        return self.nodelist.render(context)
      File "/mnt/c/Users/young/Desktop/project/myapp/lib/python3.6/site-packages/django/template/base.py", line 937, in render
        bit = node.render_annotated(context)
      File "/mnt/c/Users/young/Desktop/project/myapp/lib/python3.6/site-packages/django/template/base.py", line 904, in render_annotated
        return self.render(context)
      File "/mnt/c/Users/young/Desktop/project/myapp/lib/python3.6/site-packages/django/template/loader_tags.py", line 62, in render
        result = block.nodelist.render(context)
      File "/mnt/c/Users/young/Desktop/project/myapp/lib/python3.6/site-packages/django/template/base.py", line 937, in render
        bit = node.render_annotated(context)
      File "/mnt/c/Users/young/Desktop/project/myapp/lib/python3.6/site-packages/django/template/base.py", line 904, in render_annotated
        return self.render(context)
      File "/mnt/c/Users/young/Desktop/project/myapp/lib/python3.6/site-packages/django/template/defaulttags.py", line 209, in render
        nodelist.append(node.render_annotated(context))
      File "/mnt/c/Users/young/Desktop/project/myapp/lib/python3.6/site-packages/django/template/base.py", line 904, in render_annotated
        return self.render(context)
      File "/mnt/c/Users/young/Desktop/project/myapp/lib/python3.6/site-packages/django/template/defaulttags.py", line 443, in render
        url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app)
      File "/mnt/c/Users/young/Desktop/project/myapp/lib/python3.6/site-packages/django/urls/base.py", line 90, in reverse
        return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))
      File "/mnt/c/Users/young/Desktop/project/myapp/lib/python3.6/site-packages/django/urls/resolvers.py", line 668, in _reverse_with_prefix
        raise NoReverseMatch(msg)
    django.urls.exceptions.NoReverseMatch: Reverse for 'series_detail' with keyword arguments '{'slug': ''}' not found. 1 pattern(s) tried: ['(?P<slug>[^/]+)\\/$']
    [22/May/2019 20:03:09] "GET / HTTP/1.1" 500 167889
    [22/May/2019 20:03:09] "GET /favicon.ico HTTP/1.1" 301 0
    Internal Server Error: /favicon.ico/
    Traceback (most recent call last):
      File "/mnt/c/Users/young/Desktop/project/myapp/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
        response = get_response(request)
      File "/mnt/c/Users/young/Desktop/project/myapp/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response
        response = self.process_exception_by_middleware(e, request)
      File "/mnt/c/Users/young/Desktop/project/myapp/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response
        response = wrapped_callback(request, *callback_args, **callback_kwargs)
      File "/mnt/c/Users/young/Desktop/project/myapp/blog/views.py", line 20, in series_pg
        series = Series.objects.get(slug=slug)
      File "/mnt/c/Users/young/Desktop/project/myapp/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method
        return getattr(self.get_queryset(), name)(*args, **kwargs)
      File "/mnt/c/Users/young/Desktop/project/myapp/lib/python3.6/site-packages/django/db/models/query.py", line 408, in get
        self.model._meta.object_name
    blog.models.Series.DoesNotExist: Series matching query does not exist.
    [22/May/2019 20:03:09] "GET /favicon.ico/ HTTP/1.1" 500 71415

1 个答案:

答案 0 :(得分:1)

您应该在series_pg视图中检查对象是否存在。它给出Series.DoesNotExist。因此,如果找不到,请显示404页面。

from django.shortcuts import get_object_or_404

# ...

def series_pg(request, slug):
    series = get_object_or_404(Series, slug=slug)
    season = Season.objects.filter(series=series).order_by("season_nr")
    episode = Episode.objects.filter(series=series).order_by("date")
    content_dict = {

        'series':series,
        'season':season,
        'episode':episode,
    }

    return render(request, 'series.html', content_dict)