Django passing the value of the form in Django-forms - django

I have 2 models WorkoutCategory and workout with a ForeignKey with workout_Category in catig
in my template i have a collapsed div "WorkoutCategory" include a collapse form "to save in workoutmodel
the question is how I should pass the catig_id if it's not included in the form
below screenshot to simplify my idea
collapsed div for woroutcategory and the form
models:
from django.db import models
# Create your models here.
class WorkoutCategory(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.name
class Workout(models.Model):
catig = models.ForeignKey(WorkoutCategory,null=True, on_delete=models.CASCADE)
workout_name = models.CharField(max_length=250)
video_link = models.CharField(max_length=300)
def __str__(self):
return self.workout_name
the Form:
from django.forms import *
from .models import *
from django import forms
class CreateWorkoutForm(ModelForm):
class Meta:
model = Workout
exclude = ['catig']
widgets = {
'workout_name' : forms.TextInput(attrs={'class':'form-control','placeholder':'Workout Name'}),
'video_link' : forms.URLInput(attrs={'class':'form-control','placeholder':'https://www.youtube.com/ ...'}),
}
the Template:
{% for catg in allcetgs %}
<br>
<div class="card-header" data-toggle="collapse" href="#multiCollapseExample{{catg.id}}" role="button" aria- expanded="false" aria-controls="multiCollapseExample{{catg.id}}">
{{catg.name}}</div>
<div class="row">
<div class="col">
<div class="collapse multi-collapse" id="multiCollapseExample{{catg.id}}">
<div class="col">
<br>
<div class="btn btn-success" data-toggle="collapse" href="#addingworkout{{catg.id}}" role="button" aria-expanded="false" aria-controls="addingworkout{{catg.id}}" style="float: right;">add workout</div>
<br> <br>
<div class="collapse multi-collapse" id="addingworkout{{catg.id}}" >
<form method="POST" action="">
{% csrf_token %}
<div class="form-row">
<div class="col">
{{workoutForm.workout_name}}
</div>
<div class="col">
{{workoutForm.video_link}}
</div>
<button type="submit" class="btn btn-primary">Save</button>
</div>
</form>
</div>
</div>
<br>
<table class="table">
<thead>
<tr>
<th scope="col">Workout Name</th>
<th scope="col">Youtube Link</th>
</tr>
</thead>
<tbody>
{% for wkout in catg.workout_set.all %}
<tr>
<td>{{wkout.workout_name}}</td>
<td>check video</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
I don't want the user it set the catig_id since it's already the parent div of the form. how should I pass that catig_id value

# You don't need to exclude the catig field in your form
class CreateWorkoutForm(ModelForm):
class Meta:
model = Workout
widgets = {
'workout_name' : forms.TextInput(attrs={'class':'form-control','placeholder':'Workout Name'}),
'video_link' : forms.URLInput(attrs={'class':'form-control','placeholder':'https://www.youtube.com/ ...'}),
}
# you can have the value of catig_id in the hidden input
<div class="collapse multi-collapse" id="addingworkout{{catg.id}}" value="{{catg.id}}">
<form id="addingworkout">
<div class="form-row">
<input type="hidden" name="catig" value="{{catg.id}}">
<div class="col">
{{workoutForm.workout_name}}
</div>
<div class="col">
{{workoutForm.video_link}}
</div>
<button type="submit" class="btn btn-primary">Save</button>
</div>
</form>
</div>

Related

Django CreateView form in modal not show

I have a simple CRUD for a table named Clasificacion. The problem is I would like use a Modal for insert record, but actually I don't use the Django form, instead I declared a normal form with all the fields one by one, but I would like use the From, but is not posible for me show the form content, instead the modal shows empty with the ok button.This table has a model declared as:
class Clasificaciones(models.Model):
clasificacion=models.CharField(max_length=30)
detalles=models.CharField(max_length=1000)
This is How I declared the ListView and the CreateView
class ClasificacionesListView(ListView):
model = Clasificaciones
template_name = 'clasificacion/index.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['title'] = "Lista de clasificaciones"
return context
class ClasificacionesCreateView(SuccessMessageMixin, CreateView):
model = Clasificaciones
form_class = ClasificacionesForm
template_name = 'clasificacion/index.html'
success_url = reverse_lazy('clasificaciones')
success_message = "Insertado correctamente!!!!"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
return context
and this is the index.html with the modal. The modal is in other directory but not works if I put in the same index.html file
{% extends "starter.html" %}
{% block content %}
<div class="content-wrapper">
<section class="content-header">
<div class="container-fluid">
<div class="row mb-2">
<div class="col-sm-6">
<div class="pull-right">
<button type="button" class="btn btn-success" data-toggle="modal" data-target="#modalAddClasificacion">Nueva clasificación</button>
</div>
</div><!-- /.col -->
</div><!-- /.row -->
</div><!-- /.container-fluid -->
</section>
<section class="content">
<div class="content-fluid">
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-header">
<h3 class="card-title">Clasificaciones</h3>
</div>
<div class="card-body">
<table id="tablaClasificaciones" class="table table-bordered table-striped">
<thead>
<tr>
<th>Clasificación</th>
<th>Detalles</th>
<th></th>
</tr>
</thead>
<tbody>
{% for clasificacion in object_list %}
<tr>
<td>{{ clasificacion.clasificacion }}</td>
<td>{{ clasificacion.detalles }}</td>
<td>
<div>
<!-- Detalles -->
Editar
<a class="btn btn-link" data-toggle="modal" data-target="#deleteClasificacionModal{{clasificacion.id}}"><span class="fas fa-trash text-danger"></a>
{% include 'clasificacion/modals/delete_modal.html' %}
</div>
</td>
</tr>
{% endfor %}
</tbody>
<tfoot>
<tr>
<th>Clasificación</th>
<th>Detalles</th>
<th></th>
</tr>
</tfoot>
</table>
</div>
</div>
</div>
</div>
</div>
</section>
</div>
{% include 'clasificacion/modals/add_modal.html' %}
{% endblock %}
and the modal code, commented the inputs, this way works, but I would like use form
<div class="modal fade" id="modalAddClasificacion">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Adicionar clasificación</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Cerrar">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="row">
<form id="addclasificacion" method="POST">
{% csrf_token %}
<div class="row">
{% for field in form.visible_fields %}
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>{{ field.label }}</strong>
{{ field }}
</div>
</div>
{%endfor%}
<!-- <div class="col-12">
<div class="form-group">
<strong>Clasificación:</strong>
<input type="text" name="clasificacion" class="form-control" placeholder="Clasificación">
</div>
</div>
<div class="col-12">
<div class="form-group">
<strong>Detalles:</strong>
<textarea class="form-control" style="height:150px" name="detalles" placeholder="Detalles"></textarea>
</div>
</div> -->
<div class="col-xs-12 col-sm-12 col-md-12 text-center">
<button type="submit" class="btn btn-primary">Insertar</button>
</div>
</div>
</form>
</div>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
It not works because I must add to context variable the form, in this case the Form to Categoria model. Also I must add to Create form, because I don't use a create template.
So this is the answer:
class ClasificacionesListView(ListView):
model = Clasificaciones
template_name = 'clasificacion/index.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['title'] = "Lista de clasificaciones"
context['form'] = ClasificacionesForm()#here the detail.
return context

How to render error or validation messages to ModelForm in 2022

I've spent several hours researching on the internet, especially the official Django documentation, but still it is not clear to me which is the best option in 2022 (since almost all questions I read on SO are > 6 yo)
and there are diverse opinions on whether crispy forms is better or not.
Is still crispy forms a recommended option?
How can I (and what is the most recommended way to) get the typical validation error messages?
Like: "this field is mandatory" or "this input accepts numbers only"? I've seen some Django pages using those default messages but I don't know how to show them in my ModelForm fields.
Lets say I have the following model:
class Project(models.Model):
project_name = models.CharField(max_length=250, null=False, blank=False)
status = models.CharField(
max_length=250,
null=True,
blank=True,
default=PROJECT_STATUS_DEFAULT,
choices=PROJECT_STATUS,
)
creation_date = models.DateField(max_length=250, null=False, blank=False)
project_code = models.IntegerField(null=True, blank=True)
notes = models.CharField(max_length=250, null=True, blank=True)
And for the Project model I have the following ModelForm:
class CreateNewProjectForm(ModelForm):
creation_date = forms.DateField(widget=forms.DateInput(format = '%d/%m/%Y'), input_formats=settings.DATE_INPUT_FORMATS) #UK Date format
class Meta:
model = Project
fields = '__all__'
The view, when I try to create a new object Project:
def add_new_project(request):
context = {}
if request.method == 'POST':
form = CreateNewProjectForm(request.POST)
if form.is_valid():
form.save()
return redirect('project_page')
else:
print (form.errors)
form = CreateNewProjectForm()
context['form'] = form
return render(request, 'new_project.html', context)
HTML part:
<div class="card h-100">
<div class="card-header project-page-header">
<h3>Create A New Project</h3>
</div>
<div class="card-body px-0 new-project-card-body">
<div class="cardItem">
<div class="row">
<div class="col">
<div class="row">
<div class="tab-pane fade show active" id="general">
<form id="newProjectForm" method="POST" action="new_project">
{% csrf_token %}
<div class="accordion accordion-flush" id="accordionGeneral">
<div class="accordion-item">
<h2 class="accordion-header" id="general-headingOne">
<button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#general-collapseOne" aria-expanded="false" aria-controls="general-collapseOne">
Details
</button>
</h2>
<div id="general-collapseOne" class="accordion-collapse collapse show" aria-labelledby="general-headingOne" data-bs-parent="#accordionGeneral">
<div class="accordion-body">
<div class="row">
<div class="col-5">
<ul class="list-unstyled">
<li class="mt-3">
<div class="row">
<div class="col-sm ph-tabs-field-label">
Project Name
</div>
<div class="col-sm">
<input type="text" name="project_name" class="form-control" aria-label="Project Name">
</div>
</div>
</li>
<li class="mt-3">
<div class="row">
<div class="col-sm ph-tabs-field-label">
Status
</div>
<div class="col-sm">
<select name="status" class="selectpicker show-tick w-100" aria-label="Status">
{% for status in project_status %}
{% if forloop.first %}
<option value="{{ status.id }}" selected>{{ status.text }}</option>
{% else %}
<option value="{{ status.id }}">{{ status.text }}</option>
{% endif %}
{% endfor %}
</select>
</div>
</div>
</li>
<li class="mt-3">
<div class="row">
<div class="col-sm ph-tabs-field-label">
Creation Date
</div>
<div class="col-sm">
<input type="text" name="creation_date" class="form-control">
</div>
</div>
</li>
<li class="mt-3">
<div class="row">
<div class="col-sm ph-tabs-field-label">
Project Code
</div>
<div class="col-sm">
<input type="text" name="project_code" class="form-control">
</div>
</div>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
<div class="accordion-item">
<h2 class="accordion-header" id="general-headingThree">
<button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#general-collapseThree" aria-expanded="false" aria-controls="general-collapseThree">
Note
</button>
</h2>
<div id="general-collapseThree" class="accordion-collapse collapse" aria-labelledby="general-headingThree" data-bs-parent="#accordionGeneral">
<div class="accordion-body"><textarea name="notes" class="form-control" rows="7"></textarea></div>
</div>
</div>
<button type="submit" id="projectEditBtn" form="newProjectForm" class="btn btn-info rounded-0">Save</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
I saw solutions like this, but the problem is that my form fields are spread over different accordions, I can't use something like {% if form.errors %}, I need something more specific for each field.
First update your views like this
def add_new_project(request):
context = {}
if request.method == 'POST':
form = CreateNewProjectForm(request.POST)
if form.is_valid():
form.save()
return redirect('project_page')
else:
print (form.errors)
context['form'] = form
return render(request, 'new_project.html', context)
context['form'] = CreateNewProjectForm()
return render(request, 'new_project.html', context)
You can specify error for each field like this
{% if form.field_name.errors %}
{{ form.field_name.errors }}
{% endif %}

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"> </th>
<th class="empty"> </th>
<th class="empty"> </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> <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></td>
<td> <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></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>
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">

save() prohibited to prevent data loss due to unsaved related object 'user'

i am trying to save data in a table when a user click the checkout button of add to cart but it is showing me the above mention error i am unable to understand and one more thing is happening when i logout my the cart which i saved also got erased is it shomehow related to that i don't know
here is my views.py for checkout button
class Checkout(View):
def post (self, request,):
user = request.session.get('user')
ids = (list(request.session.get('cart').keys()))
sections = Section.get_sections_by_id(ids)
for section in sections:
order = Order(user = User(id=user),
section = section,
price = section.price,
)
order.save()
my views.py for cart.html
class Cart(View):
def get (self, request):
ids = (list(request.session.get('cart').keys()))
sections = Section.get_sections_by_id(ids)
print(sections)
return render(request, 'cart.html', {'sections': sections})
my urls.py
urlpatterns = [
path('cart/', Cart.as_view(),name='cart'),
path('Check-Out/', Checkout.as_view(),name='checkout'),
]
my cart.html
{% extends 'base.html' %}
{% load static %}
{% load cart %}
{% load custom %}
{% block head %}
<link rel="stylesheet" href="{% static 'css/cart.css' %}">
{% endblock %}
{% block content %}
<div class="container jumbotron">
<section>
<h1>My cart</h1>
<table class="table">
<thead>
<tr>
<th scope="col">S.no</th>
<th scope="col">Subject</th>
<th scope="col">Section</th>
<th scope="col">Teacher</th>
<th scope="col">Duration</th>
<th scope="col">Price</th>
</tr>
</thead>
{% for section in sections%}
<tbody style="margin-bottom: 20px;">
<tr>
<th scope="row">{{forloop.counter}}</th>
<td>{{section.subject.name}}</td>
<td>{{section.title}}</td>
<td>{{section.teacher}}</td>
<td>{{section.content_duration}}</td>
<td>{{section.price|currency}}</td>
</tr>
</tbody>
{% endfor %}
<tfoot>
<tr>
<th> Total</th>
<th></th>
<th></th>
<th></th>
<th></th>
<th>{{sections|total_price:request.session.cart|currency}}</th>
</tr>
<hr>
</tfoot>
</table>
<button type="button" data-toggle="modal" data-target="#exampleModal" style="float: right; margin-left:5px" class="btn btn-outline-primary">Check Out</button>
<button type="button" style="float: right; margin-left:5px" class="btn btn-info">Back To Site</button>
</tfoot>
</section>
</div>
<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Please Verify</h5>
<input type="button"class="btn-close btn-link" style="text-decoration:none; border:none; font-size:20px;" data-dismiss="modal" aria-label="Close" value="X">
</div>
<div class="modal-body">
<form action="{% url 'transactions:checkout' %}" method="Post">
{% csrf_token %}
<input type="submit" class="btn float-right btn-primary" value='Go Ahead'>
</form>
</div>
</div>
</div>
</div>
{% endblock %}
and my models.py
class Order(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE,)
section = models.ForeignKey(Section, on_delete=models.CASCADE )
price = models.FloatField(blank=False)
update_at = models.DateTimeField(auto_now=True, editable=False)
def placeorder(self):
self.save()
please help if you can an
The issue caused by this line:
order = Order(user = User(id=user)
Using User(id=user) means you want to create an unsaved User and use it in an unsaved Order and then saving the order, but this will not work because you haven't saved the User yet, as mentioned by the error.
You can just simply just use the existing user in the order like this:
order = Order(user=user, section=section, price=section.price)
order.save()

The delete view doesn't erase the correspondent object

I'm developing the backend of my personal blog and I've create a view that delete a single tag of the post.
views.py
from django.shortcuts import get_object_or_404, redirect, render
from django.utils.text import slugify
from .forms import BlogTagForm
from .models import BlogTag
def deleteBlogTag(request, slug_tag):
if request.method == 'POST':
tag = BlogTag.objects.get(slug_tag=slug_tag)
tag.delete()
return redirect('tag_list')
models.py
from django.db import models
from django.urls import reverse
class BlogTag(models.Model):
tag_name = models.CharField(
'Tag',
max_length=50,
help_text="Every key concept must be not longer then 50 characters",
unique=True,
)
slug_tag = models.SlugField(
'Slug',
unique=True,
help_text="Slug is a field in autocomplete mode, but if you want you can modify its contents",
)
def __str__(self):
return self.tag_name
def get_absolute_url(self):
return reverse("single_blogtag", kwargs={"slug_tag": self.slug_tag})
class Meta:
ordering = ['tag_name']
urls.py
path("tags/", views.listTagAdmin, name='tag_list_admin'),
path("create-tag/", views.createBlogTag, name='create_tag'),
path("update-tag/<str:slug_tag>/", views.updateBlogTag, name='update_tag'),
path("delete-tag/<str:slug_tag>/", views.deleteBlogTag, name='delete_tag'),
tag_list.html
<table class="table table-striped">
<thead class="bg-secondary text-white">
<tr>
<th colspan="3"><h1 class="text-center"><strong>Tag List</strong></h1></th>
</tr>
<tr>
<th colspan="1">Tag</th>
<th colspan="1">Related Posts</th>
<th class="text-center" colspan="1">Actions</th>
</tr>
</thead>
<tbody>
{% for tag in tag_list %}
<tr>
<td colspan="1">{{ tag.tag_name }}</td>
<td colspan="1">{{ tag.tag_blogpost.count }}</td>
<td colspan="1">
<div class="row justify-content-md-center">
<a class="btn btn-success btn-sm mx-1" href="{% url 'update_tag' slug_tag=tag.slug_tag %}">Update</a>
<button class="btn btn-danger btn-sm mx-1" type="button" data-toggle="modal" data-target="#deleteModal">Delete</button>
<div class="modal fade" id="deleteModal" tabindex="-1" role="dialog" aria-labelledby="deleteModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h2 class="modal-title text-center" id="deleteModalLabel">Delete Request</h2>
</div>
<div class="modal-body">
<h3>Are you sure to delete this tag?</h3>
<h1 class="py-4"><em><strong>{{ tag.tag_name }}</strong></em></h1>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary btn-sm" data-dismiss="modal">No, don't do this</button>
<form action="{% url 'delete_tag' slug_tag=tag.slug_tag %}" method="POST">
{% csrf_token %}
<button class="btn btn-danger btn-sm" type="submit" name="button">Yes, delete it</button>
</form>
</div>
</div>
</div>
</div>
</div>
</td>
</tr>
{% endfor %}
</tbody>
</table>
The problem is that it's not possible to delete every single objects of the list but only the first object. Even if I try to delete the last object I delete the first object instead of the last.
Where I've wrong?
All your modal forms are named the same, hence it will pick one. If it searches for a specific id, it will pick one. In order to solve this, you should give your modals different ids:
<tbody>
{% for tag in tag_list %}
<tr>
<td colspan="1">{{ tag.tag_name }}</td>
<td colspan="1">{{ tag.tag_blogpost.count }}</td>
<td colspan="1">
<div class="row justify-content-md-center">
<a class="btn btn-success btn-sm mx-1" href="{% url 'update_tag' slug_tag=tag.slug_tag %}">Update</a>
<button data-target="#deleteModal{{ tag.pk }}" class="btn btn-danger btn-sm mx-1" type="button" data-toggle="modal">Delete</button>
<div class="modal fade" id="deleteModal{{ tag.pk }}" tabindex="-1" role="dialog" aria-labelledby="deleteModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h2 class="modal-title text-center" id="deleteModalLabel">Delete Request</h2>
</div>
<div class="modal-body">
<h3>Are you sure to delete this tag?</h3>
<h1 class="py-4"><em><strong>{{ tag.tag_name }}</strong></em></h1>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary btn-sm" data-dismiss="modal">No, don't do this</button>
<form action="{% url 'delete_tag' slug_tag=tag.slug_tag %}" method="POST">
{% csrf_token %}
<button class="btn btn-danger btn-sm" type="submit" name="button">Yes, delete it</button>
</form>
</div>
</div>
</div>
</div>
</div>
</td>
</tr>
So here we added a suffix to the id of the <div class="modal fade" id="deleteModal{{ tag.pk }}" ...>, and used the same id in the <button target="#deleteModal{{ tag.pk }}" ...>.