I have this error delete() missing 1 required positional argument: 'id' when I click on the delete button

when I click on the delete button, I am supposed to make it delete from my database, but instead I got this error: delete() missing 1 required positional argument: 'id' as shown in the picture below: enter image description here

urlpatterns = [

        path('', views.login_user, name='login'),
        path('home/', views.home, name='home'),
        path('allstaff/', views.allstaff, name='allstaff'),
        #path('delete_order/<str:pk>/', views.deleteOrder, name="delete_order"),
        path('delete', views.delete, name='delete'),
        path('logout/', views.logout_view, name='logout'),
        path('register/', views.register_view, name='register'),
        path('edit-register/', views.edit_register_view, name='edit_register'),

def delete(request, id):
    context = {}
    user = get_object_or_404(User, id=id)
    if request.method == "POST":
        return HttpResponseRedirect("/home")
    return render(request, 'delete.html', context)

{% extends "home.html" %}
{% block content %}
table {
    border:solid black 1px;

td, th {
    border-left:solid black 1px;
    border-top:solid black 1px;

th {
    border-top: none;

td:first-child, th:first-child {
     border-left: none;


   <div style="padding-left:16px">

 <div class="form-block">
    <th>Staff Name</th>
      <th>Staff Username</th>
      <th>Date Joined</th>
         {% for user in allusername %}
        <td>{{user.first_name}} {{user.last_name}}</td><td>{{user.username}}</td><td>{{}}</td><td>{{user.date_joined}}</td><td><a class="btn btn-sm btn-info" href="{}">Update</a></td><td><a class="btn btn-sm btn-danger" href="/delete">Delete</a></td>


{% endfor %}


{% endblock %}

What did I miss out? How do I get it to work so that when I click on the delete button, it will auto delete from my database?

Answers: 1

Answered by Willem Van Onsem, Sept. 14, 2021, 10:15 a.m.

The URL should include the primary key (or another unique) field to delete this user, so:

path('delete/<int:id>/', views.delete, name='delete'),

Then in the template, we make a mini-form that will include the id of the User object to remove:

{% for user in allusername %}
    <form action="{% url 'delete' %}" method="post">
        {% csrf_token %}
        <button type="submit" class="btn btn-sm btn-danger">Delete</button>
{% endfor %}

Finally in your view you delete the User object without specifying the id again: you already have the right object since you fetch the User with id=id:

from django.shortcuts import redirect

def delete(request, id):
    user = get_object_or_404(User, id=id)
    if request.method == 'POST':
        return redirect('home')
    return render(request, 'delete.html')