У меня возникает эта ошибка, когда я пытаюсь опубликовать новое сообщение, это не вызывало у меня ошибки до тех пор, пока я не добавил функцию загрузки файла на страницу создания сообщения, и теперь, когда я пытаюсь создавать сообщения после загрузки файлов, получаю эту ошибку

NoReverseMatch в / post / new / Реверс для «пост-детализация» не найден. "post-detail" не является допустимой функцией просмотра или именем шаблона.

Вот мои коды views.py ниже

from django.contrib import messages
from django.contrib.auth.mixins import (LoginRequiredMixin, UserPassesTestMixin)
from django.contrib.auth.models import User
from django.urls import reverse_lazy, reverse
from django.http import HttpResponseRedirect, Http404
from django.shortcuts import render, get_object_or_404
from django.views.generic import (ListView, DetailView, CreateView,
                                  UpdateView, DeleteView)

from .models import Post, Comment
from django.core.files.storage import FileSystemStorage
from .forms import CommentForm
from . import models



def home(request):
    context = {
        'posts': Post.objects.all()
    }
    return render(request, 'blog/home.html', context)

def upload(request):
    if request.method == 'POST':
        uploaded_file = request.FILES['document']
        fs = FileSystemStorage()
        fs.save(uploaded_file.name, uploaded_file)
    return render(request, 'blog/post_form.html')


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

class UserPostListView(ListView):
    model = Post
    template_name = 'blog/user_posts.html'
    context_object_name = 'posts'
    paginate_by = 6

    def get_queryset(self):
        user = get_object_or_404(User, username=self.kwargs.get('username'))
        return Post.objects.filter(author=user).order_by('-date_posted')


class PostDetailView(DetailView):
    model = Post


def post_comment(request, id, slug):
    post = get_object_or_404(Post, id=id, slug=slug)
    comments = Comment.objects.filter(post=post).order_by('-id')

    if request.method == 'POST':
        comment_form = CommentForm(request.POST or None)
        if comment_form.is_valid():
            content = request.POST.get('content')
            comment = Comment.objects.create(post=post, user=request.user, content=content)
            comment.save()
            return HttpResponseRedirect(post.get_absolute_url())

    else:
        comment_form = CommentForm()

    context = {'comments': comments,
               'comment_form': comment_form}
    return render(request, 'blog/post_comment.html', context)


class PostCreateView(LoginRequiredMixin, CreateView):
    model = models.Post
    fields = ['title', 'content', 'group', 'file']

    def form_valid(self, form):
        form.instance.author = self.request.user
        return super().form_valid(form)


class PostUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
    model = Post
    fields = ['title', 'content']

    def form_valid(self, form):
        form.instance.author = self.request.user
        return super().form_valid(form)

    def test_func(self):
        post = self.get_object()
        if self.request.user == post.author:
            return True
        return False

class PostDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView):
    model = Post
    success_url = reverse_lazy('posts:blog-home')

    def test_func(self):
        post = self.get_object()
        if self.request.user == post.author:
            return True
        return False


def about(request):
    return render(request, 'blog/about.html', {'title': 'About'})

Вот мои коды urls.py приложения

from django.urls import path
from .views import (PostListView, PostCreateView,
                    PostUpdateView, PostDetailView, PostDeleteView, UserPostListView)
from . import views

app_name = 'posts'

urlpatterns = [
    path('', PostListView.as_view(), name="blog-home"),
    path('user/<str:username>', UserPostListView.as_view(), name="user-posts"),
    path('post/<int:pk>/', PostDetailView.as_view(), name="post-detail"),
    path("post/<int:pk>/", views.post_comment, name="comments"),
    path('post/new/', PostCreateView.as_view(), name="post-create"),
    path('post/<int:pk>/update', PostUpdateView.as_view(), name="post-update"),
    path('post/<int:pk>/delete', PostDeleteView.as_view(), name="post-delete"),
    path('about/', views.about, name="blog-about"),

]

Вот и коды моего проекта urls.py

from django.contrib import admin
from django.contrib.auth import views as auth_views
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
from users import views as user_view

urlpatterns = [
    path('admin/', admin.site.urls),
    path('register/', user_view.register, name="register"),
    path('profile/', user_view.profile, name="profile"),
    path('groups/',include("groups.urls", namespace="groups")),
    path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name="login"),
    path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name="logout"),
    path('password-reset/', auth_views.PasswordResetView.as_view(template_name='users/password_reset.html'), name="password_reset"),
    path('password-reset/done/', auth_views.PasswordResetDoneView.as_view(template_name='users/password_reset_done.html'), name="password_reset_done"),
    path('password-reset-confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name='users/password_reset_confirm.html'), name="password_reset_confirm"),
    path('password-reset-complete/', auth_views.PasswordResetCompleteView.as_view(template_name='users/password_reset_complete.html'), name="password_reset_complete"),
    path('', include("blog.urls")),
]

if settings.DEBUG:
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Вот мои коды шаблонов post_detail.html

{% extends "blog/base.html" %}
{% block content %}

        <article class="media content-section">
              <img class="rounded-circle article-img" src="{{ object.author.profile.image.url }}">
              <div class="media-body">
                <div class="article-metadata">
                  <a class="mr-2" href="{% url 'posts:user-posts' object.author.username %}">{{ object.author }}</a>
                  <small class="text-muted">{{ object.date_posted|date:"F d, Y" }}</small>
                    {% if object.author == user %}
                        <div>
                            <a class="btn btn-secondary btn-sm mt-1 mb-1" href="{% url 'posts:post-update' object.id %}">Update</a>
                            <a class="btn btn-danger btn-sm mt-1 mb-1" href="{% url 'posts:post-delete' object.id %}">Delete</a>
                        </div>
                    {% endif %}
                </div>
                <h2 class="article-title">{{ object.title }}</h2>
                <p class="article-content">{{ object.content }}</p>
              </div>
        </article>

{% endblock %}

Приложение работает так: когда вы публикуете сообщения, они появляются на главной странице, которая контролируется user_posts.html, код приведен ниже.

{% extends "blog/base.html" %}
{% block content %}
    <h2 class="mb-3">Posts by {{ views.kwargs.username }} ({{ page_obj.paginator.count }})</h2>
    {% for post in posts %}
        <article class="media content-section">
              <img class="rounded-circle article-img" src="{{ post.author.profile.image.url }}">
              <div class="media-body">
                <div class="article-metadata">
                  <a class="mr-2" href="{% url 'posts:user-posts' post.author.username %}">{{ post.author }}</a>
                  <small class="text-muted">{{ post.date_posted|date:"F d, Y" }}</small>
                </div>
                <h2><a class="article-title" href="{% url 'posts:post-detail' post.id %}">{{ post.title }}</a></h2>
                <p class="article-content">{{ post.content }}</p>
              </div>
        </article>
    {% endfor %}
    {% if is_paginated %}

        {% if page_obj.has_previous %}
            <a class="btn btn-outline-info mb-4" href="?page=1">First</a>
            <a class="btn btn-outline-info mb-4" href="?page={{ page_obj.previous_page_number }}">Previous</a>
        {% endif %}

        {% for num in page_obj.paginator.page_range %}
            {% if page_obj.number == num %}
                <a class="btn btn-info mb-4" href="?page={{ num }}">{{ num }}</a>
            {% elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'3' %}
                <a class="btn btn-outline-info mb-4" href="?page={{ num }}">{{ num }}</a>
            {% endif %}
        {% endfor %}

        {% if page_obj.has_next %}
            <a class="btn btn-outline-info mb-4" href="?page={{ page_obj.next_page_number }}">Next</a>
            <a class="btn btn-outline-info mb-4" href="?page={{ page_obj.paginator.num_pages }}">Last</a>
        {% endif %}

    {% endif %}
{% endblock %}

Это ошибка, которая выделяется жирным шрифтом во время Traceback.

C: \ Users \ HOPE \ Desktop \ Django \ Blog_project \ blog \ views.py в формате form_valid return super (). form_valid (форма)

C: \ Users \ HOPE \ Desktop \ Django \ Blog_project \ blog \ models.py в get_absolute_url return reverse ('post-detail', kwargs = {'pk': self.pk})

-1
Josehope 24 Июл 2020 в 16:07

1 ответ

Лучший ответ

Проблема находится в "user_posts.html" в этой строке.

    <h2><a class="article-title" href="{% url 'posts:post-detail' post.id %}">{{ post.title }}</a></h2>

В этой строке должно быть:

    <h2><a class="article-title" href="{% url 'posts:post-detail' pk=post.id %}">{{ post.title }}</a></h2>

Если мы посмотрим на ваш urls.py -

    path('post/<int:pk>/', PostDetailView.as_view(), name="post-detail"),

Мы видим, что для доступа к этому URL используется целое число - pk. Итак, в вашем html-файле, когда вы пытаетесь вернуться к этому URL-адресу, обязательно укажите, что pk = post.id. Таким образом, django знает, какую информацию передавать в URL-адрес.

0
RMGP 24 Июл 2020 в 14:11