djangobootstrap-4django-viewsdjango-urlsdjango-2.2

Button for updating a blog post


I've a trouble to create correctly a button based on Bootstrap 4.3 with which activates the update of a post. I've created this view:

def updatePost(request, slug_post=None):
    update_post = get_object_or_404(BlogPost, slug_post=slug_post)
    form = BlogPostForm(request.POST or None, request.FILES or None, instance=update_post)
    if form.is_valid():
        update_post = form.save(commit=False)
        update_post.slug_post = slugify(update_post.title)
        update_post.save()
        return redirect('post_list')

    context = {
        'form': form,
        }
    template = 'blog/editing/create_post.html'
    return render(request, template, context)

and this path:

path("blog/<str:slug_post>/update/", views.updatePost, name='update_post'),

But when I use this button:

<a class="btn btn-primary btn-lg mt-2" href="{% url 'update_post' %}">Update</a>

I see this error message:

Reverse for 'update_post' with no arguments not found. 1 pattern(s) tried: ['blog/(?P<slug_post>[^/]+)/update/$']

The strange thing is that if I write the link to the update into the address bar I can update my post. For example: I've this link to a post: /blog/title-slug-post/. If I digit /blog/title-slug-post/update/ it is possible for me to update the post.

What have I done wrong?


Solution

  • You need to include the slug_post argument in the url template tag. Right now it doesn't know what slug you want and raises an error.

    {% url 'update_post' slug_post='title-slug-post' %}
    

    If you pass the BlogPost object in the context you can also format it this way.

    {% url 'update_post' slug_post=blog_post.slug_post %}