Обратный для ‘post-detail’ с аргументами ‘(«,)’ не найден. попробован 1 шаблон (ы): [‘post/(?P[0-9] )/$’]

#python #html #django

#python #HTML #django

Вопрос:

Я работаю над небольшим проектом Django Blog, но застрял с этой ошибкой:-

 NoReverseMatch at /
Reverse for 'post-detail' with arguments '('',)' not found. 1 pattern(s) tried: ['post/(?P<pk>[0-9] )/$']
Request Method: GET
Request URL:    http://127.0.0.1:8000/
Django Version: 3.0.8
Exception Type: NoReverseMatch
Exception Value:    
Reverse for 'post-detail' with arguments '('',)' not found. 1 pattern(s) tried: ['post/(?P<pk>[0-9] )/$']
Exception Location: /home/manish/Videos/open-source/Blog-Env/lib/python3.8/site-packages/django/urls/resolvers.py in _reverse_with_prefix, line 677
Python Executable:  /home/manish/Videos/open-source/Blog-Env/bin/python
Python Version: 3.8.2
Python Path:    
['/home/manish/Videos/open-source/Blogger/mysite',
 '/usr/lib/python38.zip',
 '/usr/lib/python3.8',
 '/usr/lib/python3.8/lib-dynload',
 '/home/manish/Videos/open-source/Blog-Env/lib/python3.8/site-packages']
Server time:    Sat, 22 Aug 2020 14:40:46  0530
  

Вот коды Django:- urls.py

 from django.urls import path
from .views import (
        PostDetailView,
        PostUpdateView,
        PostDeleteView,
        PostListView,
        about,
        post_create,
        Profileview
    )

urlpatterns = [
    path("", PostListView.as_view(), name="blog-home"),
    path("about/", about, name="blog-about"),
    path("profileview/<name>", Profileview, name="blog-profile"),
    path("post/<int:pk>/", PostDetailView.as_view(), name="post-detail"),
    path("post/<int:pk>/update/", PostUpdateView.as_view(), name="post-update"),
    path("post/<int:pk>/delete/", PostDeleteView.as_view(), name="post-delete"),
    path("post_create/", post_create, name="post_create"),
]

  

Вот views.py файл:-

 from django.shortcuts import render, redirect
from django.http import HttpResponse
from .models import Post
from django.views.generic import ListView
from django.contrib.auth.models import User
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.views.generic import DetailView, UpdateView, DeleteView
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from .forms import PostForm
from django.db.models import Q

class PostDetailView(DetailView):
    model = Post


class PostListView(ListView):
    model = Post
    template_name = 'blog/home.html'
    context_object_name = 'posts'
    ordering = ['-date_posted']
............
............

  

Вот base.html файл:-

 {% load static %}

<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3 Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
    <link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg p" crossorigin="anonymous"/>
    <link rel="stylesheet" href="{% static 'blog/main.css' %}" type="text/css">
    <title></title>
  </head>
  <body>

    <header class="site-header">
      <nav class="navbar navbar-expand-md navbar-dark bg-steel fixed-top">
        <div class="container">
          <a class="navbar-brand mr-4" href="{% url 'blog-home' %}">Django Blog</a>
          <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarToggle" aria-controls="navbarToggle" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
          </button>
          <div class="collapse navbar-collapse" id="navbarToggle">
            <div class="navbar-nav mr-auto">
              <a class="nav-item nav-link" href="{% url 'blog-home' %}">Home</a>
              <a class="nav-item nav-link" href="/about">About</a>
              {% if user.is_authenticated %}
              <a class="nav-item nav-link" href="{% url 'post_create' %}">Post Create</a>
              {% endif %}
              <!--Search Bar-->
              <div class="search-bar">
                <form method="GET" action="/" style="display:inline-block; line-height:24px; border-radius: 80px">
                  <input type="text" placeholder="amp;nbsp;Search Blogs..." onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'amp;nbsp;Search Blogs...';}" name ="q" required="" size="29" style="border-radius: 80px">
                </form>
              </div>
            </div>
            <!-- Navbar Right Side -->
            <div class="navbar-nav">

              {% if user.is_authenticated %}
              <a class="nav-item nav-link" href="{% url 'profile' %}">Profile</a>
              <a class="nav-item nav-link" href="{% url 'logout' %}">Logout</a>
              {% else %}
              <a class="nav-item nav-link" href="{% url 'login' %}">Login</a>
              <a class="nav-item nav-link" href="{% url 'register' %}">Register</a>
              {% endif %}
            </div>
          </div>
        </div>
      </nav>
    </header>


    <main role="main" class="container">
      <!--Slider Start-->
      {% block slider%}

      {% endblock %}
      <!--Slider End-->
      <span style="display:inline-block; width: 3px;"></span>
      <div class="row">
        <div class="col-md-8">
            {% if messages %}
                {% for messages in messages %}
                <div class="alert alert-{{ message.tags }}">
                    {{ messages }}
                </div>
                {% endfor %}
            {% endif %}
          {% block content %}
          
          {% endblock %}
        </div>
        <div class="col-md-4">
          <div class="content-section">
            <h3>Our Sidebar</h3>
            <p class='text-muted'>You can put any information here you'd like.
              <ul class="list-group">
                <li class="list-group-item list-group-item-light">Latest Posts</li>
                <li class="list-group-item list-group-item-light">Announcements</li>
                <li class="list-group-item list-group-item-light">Calendars</li>
                <li class="list-group-item list-group-item-light">etc</li>
              </ul>
            </p>
          </div>
        </div>
      </div>
    </main>



    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2 poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ n" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft 2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
  </body>
</html>

  

Я думаю, что что-то нужно сделать с urls.py или в некоторых изменениях в base.html файл. Поскольку проблема возникает в корневом URL. Я пытался внести изменения здесь, и, похоже, ничто не устраняет эту проблему.
вот home.html файл:-

 {% extends 'blog/base.html' %} 

{% block slider%}
    <div class="slider">
        <input name="input-slider" id="input-slide-0" type="radio" class="input-slide input-slide-num" style="display: none;" />
        <input name="input-slider" id="input-slide-1" type="radio" class="input-slide input-slide-num" style="display: none;" />
        <input name="input-slider" id="input-slide-2" type="radio" class="input-slide input-slide-num" style="display: none;" />
        <input name="input-slider" id="input-slide-3" type="radio" class="input-slide input-slide-num" style="display: none;" />
        <input name="input-slider" id="input-slide-autoplay" type="radio" class="input-slide" checked style="display: none;" />
        <ul>
            <li class="slide-0"></li>
            <li class="slide-1"></li>
            <li class="slide-2"></li>
            <li class="slide-3"></li>
        </ul>

        <div class="slide-description">
            <label class="slide-0">
                <h1 class="text-slide">{{ mostliked1.title }}</h1>
                <h5>{{mostliked1.content|truncatechars:70}}</h5>
                <a href="{% url 'post-detail' mostliked1.id %}" class="readmorebutton">Read More</a>
            </label>
            <label class="slide-1">
                <h1 class="text-slide">{{ mostliked2.title }}</h1>
                <h5>{{mostliked2.content|truncatechars:70}}</h5>
                <a href="{% url 'post-detail' mostliked2.id %}" class="readmorebutton">Read More</a>
            </label>
            <label class="slide-2">
                <h1 class="text-slide">{{ mostliked3.title }}</h1>
                <h5>{{mostliked3.content|truncatechars:70}}</h5>
                <a href="{% url 'post-detail' mostliked3.id %}" class="readmorebutton">Read More</a>
            </label>
            <label class="slide-3">
                <h1 class="text-slide">{{ mostliked4.title }}</h1>
                <h5>{{mostliked4.content|truncatechars:70}}</h5>
                <a href="{% url 'post-detail' mostliked4.id %}" class="readmorebutton">Read More</a>
            </label>
        </div>

        <div class="slider-dot">
            <label class="slide-0" for="input-slide-0"></label>
            <label class="slide-1" for="input-slide-1"></label>
            <label class="slide-2" for="input-slide-2"></label>
            <label class="slide-3" for="input-slide-3"></label>
        </div>
    </div>
{% endblock %} 

{% block content %} 
    {% for post in posts %}
        <article class="media content-section">
            <div class="media-body">
                <div class="article-metadata">
                    <a class="mr-2" href="{% url 'blog-profile' name=post.author %}">{{ post.author }}</a>
                    <small class="text-muted">{{ post.date_posted }}</small>
                </div>
                <h2><a class="article-title" href="{% url 'post-detail' post.id %}">{{ post.title }}</a></h2>
                <p class="article-content">{{ post.content }}</p>
            </div>
        </article>
    {% endfor %}
{% endblock%}

  

Комментарии:

1. покажите нам шаблон PostListView

2. Я добавил @iklinac, посмотрим, сможете ли вы что-нибудь найти.

3. похоже, вы не установили наиболее понравившиеся идентификаторы «{% url ‘post-detail’ mostliked1.id %}», до 4, вы должны попытаться закомментировать эту часть, чтобы увидеть, работает ли это, и получателем будет остальная часть PostListView

4. как я уже сказал, вы не установили mostliked в PostListView, который является источником проблемы, поэтому вы должны использовать этот конкретный код в PostListView

5. {% url 'post-detail' post.id %} пожалуйста, измените это на {% url 'post-detail' pk=post.id %} . Затем мы передаем значение argument_name = value . Пожалуйста, измените подобным образом во всех шаблонах.