Search code examples
djangobootstrap-modal

Django - Deleting using modal: show and delete only the first item from the table


Please help me understand the problem. I try to use the modal to delete each line separately but instead of displaying and deleting my actual line, it always displays and deletes the first line in the table. Where am I wrong with the code? Below my settings. Thank you very much.

models.py

class Post(models.Model):

class DisplayOnlyPublicat(models.Manager):
    def get_queryset(self):
        return super().get_queryset() .filter(status='publicat')

options =(
    ('draft', 'nepublicat'),
    ('publicat', 'publicat')
)

title = models.CharField(max_length=250)
poster = models.ImageField ( upload_to ='posts/', default='posts/poster_articole_pp.jpg')
category = models.ForeignKey(Category, on_delete=models.SET_DEFAULT, default=1)
slug = models.SlugField(max_length=250, unique_for_date='publish')
publish = models.DateTimeField(default=timezone.now) 
author = models.ForeignKey (User, null=True, on_delete=models.SET_NULL, related_name='profipedia_posts')
short_content = models.TextField(null=True)
# content = models.TextField()
# content = RichTextField()
content = RichTextUploadingField(external_plugin_resources=[( 'emojione', '/static/vendor/ckeditor_plugins/emojione/' , 'plugin.js', )],)
status = models.CharField(max_length=10, choices=options, default='draft')
id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False)
objects = models.Manager() #denumire initiala 
dop = DisplayOnlyPublicat() # denumire custom

def get_absolute_url(self):
    return reverse('posts:articol', args=[self.slug])
    

# sa deschida articolul pe baza de denumire(slug) din sectiunea admin indiferent de statusul articolului (publicat/nepublicat)
# def get_absolute_url_adm(self):
#     return reverse('posts:articolAdm', args=[self.slug])

class Meta:
    ordering = ('-publish',)

def __str__(self):
    return self.title

views.py

def delete_articol(request, articol_id):
    post = Post.objects.get(pk=articol_id)
    post.delete()
    messages.success(request, "Articolul a fost sters!")
    return redirect('posts:articoleAdm')

urls.py

urlpatterns = [
    
    path('', views.articole, name='articole'),
   
    path('articole-admin/', views.articoleAdm, name='articoleAdm'),
    path('<slug:post>/', views.articol, name='articol'),
    path('articole-admin/creare-articol/', views.creareArticol, name='creareArticol'),
    path('articole-admin/<pk>/', views.articolAdm, name='articolAdm'),
    path('modificare-articol/<str:pk>/', views.modificareArticol, name='modificareArticol'),
    path('sterge-articol/<articol_id>/', views.delete_articol, name='stergeArticol'),
    path('filtru/<category>', views.CatListView.as_view(), name='categorieArticol'),
    
]

html template

<table class="data-table data-table-pagination data-table-standard responsive nowrap hover"
                        id="datatableHover" data-order='[[ 0, "desc" ]]'>
                        <thead>
                            <tr>
                                <th class="text-muted text-small text-uppercase">Poster</th>
                                <th class="text-muted text-small text-uppercase">Autor</th>
                                <th class="text-muted text-small text-uppercase">Titlu</th>
                                <th class="text-muted text-small text-uppercase">Status</th>
                                <th class="text-muted text-small text-uppercase">Categorie</th>
                                <th class="text-muted text-small text-uppercase">Data</th>
                                <th class="empty">&nbsp;</th>
                                <th class="empty">&nbsp;</th>
                                <th class="empty">&nbsp;</th>
                            </tr>
                        </thead>
                        <tbody>
                            {% for post in posts %}
                            <tr>
                                <td class="p-1"><img width="100" height="100%" class="rounded" src="{{post.poster.url}}"
                                        alt=""></td>
                                <td>{{post.author}}</td>
                                <td><a class="list-item-heading body" href="{{post.id}}">{{post.title}}</a></td>

                                {% if post.status == "draft" %}
                                <td><span class="badge rounded-pill bg-muted">{{post.status}}</span></td>
                                {% else %}
                                <td><span class="badge bg-outline-success">{{post.status}}</span></td>
                                {% endif %}

                                {% if post.category.name == "nealocata" %}
                                <td><span class="badge rounded-pill bg-muted">{{ post.category }}</span></td>
                                {% else %}
                                <td><span class="badge bg-outline-muted">{{ post.category }}</span></td>
                                {% endif %}


                                <td> <small>{{post.publish|date:"d.m.Y - H:m:s"}}</small></td>

                                <td><a href="{{post.id}}"> <button class="btn btn-icon btn-icon-only btn-foreground-alternate  edit-datatable " data-bs-toggle="tooltip" data-bs-placement="top" title="modificare articol" type="button" data-bs-delay="0"><i data-acorn-icon="eye"></i></button></a></td>

                                <td><a href="{% url 'posts:modificareArticol' post.id %}"> <button class="btn btn-icon btn-icon-only btn-foreground-alternate  edit-datatable " data-bs-toggle="tooltip" data-bs-placement="top" title="modificare articol" type="button" data-bs-delay="0"><i data-acorn-icon="edit"></i></button></a></td>

                                <td><button type="button" class="btn btn-icon btn-icon-only btn-foreground-alternate" data-bs-toggle="modal" data-bs-target="#deletePostPPP"><i data-acorn-icon="bin"></i></button></td>
                                
                                
                            </tr>
                            <!-- delete modal-->
                            <div class="modal fade" id="deletePostPPP" tabindex="-1" role="dialog" aria-hidden="true">
                                <div class="modal-dialog">
                                    <div class="modal-content">
                                        <div class="modal-header">
                                            <h5 class="modal-title">Modal title</h5>
                                            <button type="button" class="btn-close" data-bs-dismiss="modal"
                                                aria-label="Close"></button>
                                        </div>
                                        <div class="modal-body">Sigur vrei să ștergi articolul <br>
                                            <strong>"{{post.title}}"</strong>?</div>
                                        <div class="modal-footer">
                                            <button type="button" class="btn btn-secondary"
                                                data-bs-dismiss="modal">Close</button>
                                            <a href="{% url 'posts:stergeArticol' post.id %}"><button type="submit"
                                                    class="btn btn-primary">Understood</button></a>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            {% endfor %}
                        </tbody>
                    </table>

Solution

  • Your delete buttons all refer to the same modal. The issue is that all the modals you generate have the same id. When referring to that id, the first modal will be shown.

    What you should do instead is give each modal a separate id, containing e.g. the post id. Then call that specific modal in your delete button.

    Your delete button:

    <td><button type="button" class="btn btn-icon btn-icon-only btn-foreground-alternate" data-bs-toggle="modal" data-bs-target="#deletePostPPP-{{post.id}}"><i data-acorn-icon="bin"></i></button></td>
    

    Your modal:

    <!-- delete modal -->
    <div class="modal fade" id="deletePostPPP-{{post.id}}" tabindex="-1" role="dialog" aria-hidden="true">