0
votes

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?

1
In your <button> the url should have a slug right ? something like href="{% url 'update_post' 'title-slug-post' %}" As I have seen the url call should be something like <a href="{% url 'name' 'some_string_containing_relevant_data' %}">pagename</a> - Damini Ganesh
But even when you've fixed this it still won't work because button elements don't have href attributes. They are part of forms which have an action attribute which is the URL to submit to. - Daniel Roseman
Yes I've correct my mistake - Massimiliano Moraca

1 Answers

0
votes

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 %}