Реверс для 'post_edit' не найден. 'post_edit' не является допустимой функцией представления или именем шаблона - PullRequest
0 голосов
/ 10 сентября 2018

Реверс для 'post_edit' с аргументами '(' ',)' не найден.Попробован 1 шаблон (ов):

['\\^edit/\\(\\?P(?P<pk>[^/]+)\\\\d\\+\\)/\\$$']

Реверс для 'post_edit' с аргументами '(' ',)' не найден.Попробован 1 шаблон (ов):

['\\^edit/\\(\\?P(?P<pk>[^/]+)\\\\d\\+\\)/\\$$']

views.py

from django.shortcuts import render
from django.views.generic import ListView, DetailView
from . models import Topic
from django.views.generic.edit import CreateView,UpdateView
from django.urls import reverse_lazy
# Create your views here.

class BlogListView(ListView):
    model = Topic
    template_name='home.html'

class BlogDetailView(DetailView):
    model = Topic
    template_name='post_detail.html'
    context_object_name='anything_you_want'

class BlogCreateView(CreateView):
    model = Topic
    template_name = "post_new.html"
    fields='__all__'

class BlogUpdateView(UpdateView):
    model=Topic
    fields=['title','body']
    template_name='post_edit.html'

post_detail.html

{% extends 'base.html' %}

{% block content %}
   <div class="post-entry">
    <h2>{{ post.title }}</h2>
    <p>{{ post.body }}</p>
  </div>
  <a href="{% url 'post_edit' post.pk %}">+ Edit Blog Post </a>
{% endblock content %}

urls.py

from django.urls import path
from . import views

urlpatterns = [
    path('',views.BlogListView.as_view(),name='home'),
    path('post/<int:pk>', views.BlogDetailView.as_view(),name='post_detail'),
    path('post/new', views.BlogCreateView.as_view(),name='post_new'),
    path('post/<int:pk>/edit/', views.BlogUpdateView.as_view(), name='post_edit'),

]

models.py

from django.db import models
from django.urls import reverse
# Create your models here.
class Topic(models.Model):
    title=models.CharField(max_length=200)
    author=models.ForeignKey('auth.User',on_delete=models.CASCADE,)
    body=models.TextField()

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse("post_detail", args=[str(self.id)])        
![Error]: https://i.imgur.com/2LoDxtS.png
![Error]: https://i.imgur.com/o6WHFFe.png

Traceback

Environment:


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

Django Version: 2.1
Python Version: 3.7.0
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'blog',
 'accounts']
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 C:\Users\Kiran\Desktop\blog\blog_project\templates\base.html, error at line 0
   Reverse for 'post_edit' with arguments '('',)' not found. 1 pattern(s) tried: ['\\^edit/\\(\\?P(?P<pk>[^/]+)\\\\d\\+\\)/\\$$']
   1 : {% load static %}
   2 : <html>
   3 :     <head>
   4 :         <title> Django Blog</title>
   5 :         <link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:400" rel="stylesheet">
   6 :         <link rel="stylesheet" href="{% static 'css/base.css' %}">
   7 :     </head>
   8 :     <body>
   9 :             <div>
   10 :               <header>


Traceback:

File "C:\Python3.7\lib\site-packages\django\core\handlers\exception.py" in inner
  34.             response = get_response(request)

File "C:\Python3.7\lib\site-packages\django\core\handlers\base.py" in _get_response
  156.                 response = self.process_exception_by_middleware(e, request)

File "C:\Python3.7\lib\site-packages\django\core\handlers\base.py" in _get_response
  154.                 response = response.render()

File "C:\Python3.7\lib\site-packages\django\template\response.py" in render
  106.             self.content = self.rendered_content

File "C:\Python3.7\lib\site-packages\django\template\response.py" in rendered_content
  83.         content = template.render(context, self._request)

File "C:\Python3.7\lib\site-packages\django\template\backends\django.py" in render
  61.             return self.template.render(context)

File "C:\Python3.7\lib\site-packages\django\template\base.py" in render
  171.                     return self._render(context)

File "C:\Python3.7\lib\site-packages\django\template\base.py" in _render
   163.         return self.nodelist.render(context)

File "C:\Python3.7\lib\site-packages\django\template\base.py" in render
  937.                 bit = node.render_annotated(context)

File "C:\Python3.7\lib\site-packages\django\template\base.py" in render_annotated
  904.             return self.render(context)

File "C:\Python3.7\lib\site-packages\django\template\loader_tags.py" in render
  150.             return compiled_parent._render(context)

 File "C:\Python3.7\lib\site-packages\django\template\base.py" in _render
  163.         return self.nodelist.render(context)

File "C:\Python3.7\lib\site-packages\django\template\base.py" in render
  937.                 bit = node.render_annotated(context)

File "C:\Python3.7\lib\site-packages\django\template\base.py" in render_annotated
  904.             return self.render(context)

File "C:\Python3.7\lib\site-packages\django\template\loader_tags.py" in render
  62.                 result = block.nodelist.render(context)

File "C:\Python3.7\lib\site-packages\django\template\base.py" in render
  937.                 bit = node.render_annotated(context)

File "C:\Python3.7\lib\site-packages\django\template\base.py" in render_annotated
  904.             return self.render(context)

File "C:\Python3.7\lib\site-packages\django\template\defaulttags.py" in render
  442.             url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app)

File "C:\Python3.7\lib\site-packages\django\urls\base.py" in reverse
  90.     return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))

File "C:\Python3.7\lib\site-packages\django\urls\resolvers.py" in _reverse_with_prefix
  622.         raise NoReverseMatch(msg)

Exception Type: NoReverseMatch at /post/1
Exception Value: Reverse for 'post_edit' with arguments '('',)' not found. 1 pattern(s) tried: ['\\^edit/\\(\\?P(?P<pk>[^/]+)\\\\d\\+\\)/\\$$']

1 Ответ

0 голосов
/ 10 сентября 2018

Вам необходимо обновить BlogUpdateView, чтобы включить сообщение в контекст. Так это станет примерно таким,

class BlogUpdateView(UpdateView):
    model=Topic
    fields=['title','body']
    template_name='post_edit.html'

    def get_context_data(self, **kwargs):
        # Call the base implementation first to get a context
        context = super().get_context_data(**kwargs)
        context['post'] = Topic.objects.get(pk=self.kwargs['pk'])
        return context

Надеюсь, это поможет!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...