ilsurealism
ilsurealism

Reputation: 61

An error NoReverseMatch appears when I try to edit a post using UpdateView in Django

When I click on the update post link, an error appears: Reverse for 'post_detail' with no arguments not found. 1 pattern(s) tried: ['post/(?P[-a-zA-Z0-9_]+)$'].

My Post model looks like this:

class Post(models.Model):
    title = models.CharField(max_length=200, verbose_name='Заголовок')
    slug = AutoSlugField(populate_from=['title'])
    title_image = models.ImageField(upload_to=user_img_directory_path, blank=True, verbose_name='Изображение')
    description = models.TextField(max_length=500, verbose_name='Описание')
    body = FroalaField(options={
        'attribution': False,
    }, verbose_name='Текст')
    post_date = models.DateTimeField(auto_now_add=True, verbose_name='Дата публикации', db_index=True)
    post_update_date = models.DateTimeField(auto_now_add=True, verbose_name='Дата обновления публикации')
    post_status = models.BooleanField(default=True, verbose_name='Опубликовано')

    class Meta:
        ordering = ['-post_date']

    def get_absolute_url(self):
        return reverse('articles:post_detail', kwargs={'slug': self.slug})

    def __str__(self):
        return self.title

My DetailView and UpdateView classes in views.py:

from django.views.generic.detail import DetailView
from django.views.generic.edit import CreateView, UpdateView

class PostDetail(DetailView):
    model = Post
    template_name = 'articles/post_detail.html'
    context_object_name = 'post'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        return context

class UpdatePost(UpdateView):
    model = Post
    template_name = 'articles/update_post.html'
    fields = ['title', 'title_image', 'description', 'body']

My urls.py file:

from .views import PostsList, PostDetail, CreatePost, UpdatePost

app_name = 'articles'

urlpatterns = [
    path('', PostsList.as_view(), name='posts_list'),
    path('post/<slug:slug>', PostDetail.as_view(), name='post_detail'),
    path('create/', CreatePost.as_view(), name='create_post'),
    path('post/edit/<slug:slug>', UpdatePost.as_view(), name='update_post'),
]

update_post.html template looks like this:

{% extends 'layout/basic.html' %}

{% load static %}
{% load django_bootstrap5 %}

{% block content %}
<form method="post" class="form">
    {% csrf_token %}
    {{ form.media }}
    {% bootstrap_form form %}
    {% bootstrap_button button_type="submit" content="Обновить" %}
</form>

<a class="btn btn-outline-primary" href="{% url 'articles:post_detail' %}" role="button">Назад</a>

{% endblock %}

And update_post link in post_detail.html looks like this:

<a class="btn btn-outline-primary" href="{% url 'articles:update_post' post.slug %}" role="button">Обновить</a>

Please tell me how can I solve this problem?

Upvotes: 0

Views: 88

Answers (1)

Alain Bianchini
Alain Bianchini

Reputation: 4171

Good morning, the problem is that the template cannot access the slug field. You have to inject the slug into context:

class UpdatePost(UpdateView):
    model = Post
    template_name = 'articles/update_post.html'
    fields = ['title', 'title_image', 'description', 'body']
    
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['slug'] = self.object.slug
        return context

Upvotes: 1

Related Questions