I keep getting : Reverse for 'delete_entry' with arguments '('',)' not found. 1 pattern(s) tried: ['deleteentry/(?P<input_id>[^/]+)/\\Z']

Viewed 30

I am a begginer and tried to look up solutions from other threads to no avail,

Here is my views.py :

@login_required(login_url='/login')
def delete_entry(request, input_id):
    input=Diary.objects.get(pk=input_id)
    input.delete()                    
                   
    
    return redirect('home')

Here is my urls.py :

urlpatterns = [
        path('', views.welcome, name='welcome'),
        path('home', views.home, name='home'),
        path('MyEntries/', views.MyEntries, name='entries'),
        path('deleteentry/<input_id>/', views.delete_entry, name='delete_entry'),
       
    ]

Here is my html code :

<p>Hello, {{user.username}} !</p>

{%   for article in articles   %}
<p> {{ article.title}}<br>
    {{ article.description }} <br>
    {{ article.date        }}
    <div class="card-footer text-muted">


</p>
<a href="{% url 'delete_entry' input.id   %}" class="delete">Delete</a>
</div>
{% endfor %}

{%  endblock  %}
1 Answers

As the error says, this is because input.id resolves to the empty string, so likely input does not exists, or it has no id.

Likely you should work with article.id, or perhaps even more robust, use article.pk. If you delete items, you need to make a DELETE or POST request, so you can not work with a link, you use a mini-form, so:

<form action="post" method="{% url 'delete_entry' article.pk %}">
    {% csrf_token %}
    <button type="submit" class="delete">Delete</button>
</form>

The view can be further improved by using get_object_or_404, and restrict the view to only POST and DELETE requests:

from django.shortcuts import get_object_or_404
from django.views.decorators.http import require_http_methods

@login_required(login_url='/login')
@require_http_methods(["DELETE", "POST"])
def delete_entry(request, input_id):
    input = get_object_or_404(Diary, pk=input_id)
    input.delete()
    return redirect('home')
Related