P
P
PreFireSkills2021-01-17 23:19:10
Django
PreFireSkills, 2021-01-17 23:19:10

Why is the post update link not working in Django?

Hello, the url link to the post update page does not work, and the page itself works fine.
Reverse for 'edit' with keyword arguments '{'pk': ''} - error like this

views.py

@login_required
def post_edit(request, pk):
    post = Post.objects.get(id=pk)
    form = PostEditForm(instance=post)
    if request.method == 'POST':
        form = PostEditForm(data=request.POST, files=request.FILES, instance=post)
        if form.is_valid():
            post = form.save(commit=False)
            post.user = request.user
            post.save()
            messages.success(request, 'Post updated successfully')
            return render(request, 'posts/post/edit.html', )

        else:
            messages.error(request, 'Error updating your post')
    else:
        form = PostEditForm(instance=post)
    return render(request, 'posts/post/edit.html', {'form': form, 'instance': post})


urls.py
urlpatterns = [
    path('create/', views.post_create, name='create'),
    path('edit/<int:pk>/', views.post_edit, name='edit'),
]


html
{% extends "base.html" %}

{% block title %}Good job{% endblock %}

{% block content %}
  <h1> Hi, {{ user.username }}!</h1>
  <p>Your post has been successfully add to platform. </p>
    You can <a href="{% url "posts:edit" pk=post.id %}">edit your post</a>
{% endblock %}


Note: if you write pk=2, then everything works fine. Who knows what could be the problem?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
Wispik, 2021-01-18
@Wispik

an empty value, because you are passing post to a template called instance
in view.py, correct it like this:

return render(request, 'posts/post/edit.html', {'form': form, 'post': post})

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question