Newbie - Python Django - NoReverseMatch Error - python

I have gone through lots of related questions but I am not able to solve this issue so I though I will finally post it, I have an app 'Customers' which will hold a list of customers, currently there are two user levels
1) Customer - If I login as a Customer I would ONLY see my details and I must be able to edit and make changes to my information
2) Advisor - If I login as an Advisor I would see a list of customers and I would be able to make changes to any customer.
To achieve this I have an 'Edit' button when clicked redirects to a 'form' with the particular fields already populated, I can edit and save. Issue arises when I click on this 'Edit' I get this error "NoReverseMatch at /customer/". But when I directly navigate to the form by typing in, "localhost:8000/customer/1/edit" I could see the form.
Here's my views.py
#login_required
def customer_edit(request, cust_number):
# customer = get_object_or_404(Customer, pk=cust_number)
if request.method == "POST":
form = CustomerForm(request.POST)
# form = CustomerForm(request.CUSTOMER, instance=customer)
if form.is_valid():
customer = form.save(commit=False)
customer.cust_number = request.user
customer.updated_date = timezone.now()
customer.save()
return redirect('customer', pk=cust_number)
else:
form = CustomerForm()
return render(request, 'customers/customer_edit.html', {'form': form})
Here's my appname/urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^customer/$', views.customer, name='customer'),
url(r'^home/$', views.home, name='home'),
url(r'^customer/(?P<cust_number>\d+)/edit/$', views.customer_edit, name='customer_edit'),
]
Here's a part of my projectname/urls.py
url(r'', include('customers.urls', namespace="customers"))
Here's my customers/forms.py
from django import forms
from .models import Customer
class CustomerForm(forms.ModelForm):
class Meta:
model = Customer
fields = ('cust_number', 'name', 'address', 'city', 'state', 'zipcode', 'email', 'cell_phone',)
Here's my customer_edit.html
{% extends 'customers/base.html' %}
{% block content %}
<h1>Edit Customer</h1>
<form method="POST" class="customer-form">{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="save btn btn-default">Save</button>
</form>
{% endblock %}
Here's my customer.html
{% extends 'customers/base.html' %}
{% block content %}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Eagle Financial</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
</head>
<body>
<style>
body {
background-color: beige;
}
</style>
<div class="container">
<div class="row">
<div class="col-md-10 col-md-offset-1">
<div class="panel panel-primary">
<div class="panel-heading">Welcome!</div>
<div class="panel-body">
Eagle Financial Services, your Midwest Financial Services Partner.
</div>
</div>
</div>
</div>
</div>
<div class="row">
<h2 style="padding-left: 15Px">Customer Information</h2>
</div>
<div>
<table class="table table-striped table-bordered table-hover">
<thead>
<tr class="bg-info">
<th>Customer ID</th>
<th>Name</th>
<th>Address</th>
<th>City</th>
<th>State</th>
<th>Zip</th>
<th>Primary Email</th>
<th>Cell Phone</th>
<th colspan="3">Actions</th>
</tr>
</thead>
<tbody>
{% for customer in customers %}
<tr>
<td>{{ customer.cust_number }}</td>
<td>{{ customer.name }}</td>
<td>{{ customer.address }}</td>
<td>{{ customer.city }}</td>
<td>{{ customer.state }}</td>
<td>{{ customer.zipcode }}</td>
<td>{{ customer.email }}</td>
<td>{{ customer.cell_phone }}</td>
<td>Update</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</body>
</html>
{% endblock %}
Here's my error,
NoReverseMatch at /customer/
Reverse for 'customer_edit' with no arguments not found. 1 pattern(s) tried: ['customer/(?P<cust_number>\\d+)/edit/$']
Request Method: GET
Request URL: http://127.0.0.1:8000/customer/
Django Version: 1.11.1
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'customer_edit' with no arguments not found. 1 pattern(s) tried: ['customer/(?P<cust_number>\\d+)/edit/$']
I have tried trial and errors of namespaces, but not able to solve this. Please guide me. Thanks.
I am using Python - 3.6, Django - 1.11

You are doing wrong in views
customer.cust_number = request.user #Why you assign user to cust_number?
customer.updated_date = timezone.now()
customer.save()
return redirect('customer', pk=cust_number)
Update your view code with below:
from django.core.urlresolvers import reverse
#login_required
def customer_edit(request, cust_number):
# customer = get_object_or_404(Customer, pk=cust_number)
if request.method == "POST":
form = CustomerForm(request.POST)
# form = CustomerForm(request.CUSTOMER, instance=customer)
if form.is_valid():
customer = form.save(commit=False)
customer.cust_number = request.user.pk
customer.updated_date = timezone.now()
customer.save()
return reverse('customers:customer_edit', request.user.pk)
else:
form = CustomerForm()
return render(request, 'customers/customer_edit.html', {'form': form})
Use this in html
<td>Update</td>

Related

'Posts_update' object is not iterable in django

i am just try to get data from db table and show on detail page but i am getting error -'Posts_update' object is not iterable.
I have two tables posts and posts_update. in posts table i am doing CRUD operation and on each update i am adding information in posts_update table now i am trying to get information from posts_update table using mobile as a parameter but i am getting error -'Posts_update' object is not iterable.
models.py
from django.db import models
class Posts(models.Model):
title = models.CharField(max_length=200)
slug = models.SlugField(unique=True)
content = models.TextField()
mobile = models.CharField(max_length=15,default='')
class Posts_update(models.Model):
title = models.CharField(max_length=200)
slug = models.SlugField(unique=True)
content = models.TextField()
mobile = models.CharField(max_length=15,default='')
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('create/', views.create, name='create'),
path('detail/<int:post_mobile>', views.read, name='detail'),
path('delete/<int:post_id>', views.delete, name='delete'),
path('update/<int:post_id>', views.update, name='update')
]
views.py
from django.shortcuts import render, redirect
from django.template.defaultfilters import slugify
from django.http import HttpResponse
from django.contrib import messages
from .models import Posts
from .models import Posts_update
def index(request):
posts = Posts.objects.all()
return render(request, 'index.html', {
'posts': posts
})
def create(request):
if request.POST:
req = request.POST
post = Posts(title=req.get('title'), slug=slugify(req.get('title')), content=req.get('content'), mobile=req.get('mobile'))
post.save()
messages.success(request, 'The record was saved successfully')
return redirect('/')
else:
return render(request, 'create.html')
def update(request, post_id):
if request.POST:
req = request.POST
post = Posts.objects.get(id=post_id)
post.title = req.get('title')
post.slug = slugify(req.get('title'))
post.content = req.get('content')
post.mobile = req.get('mobile')
post.save()
post = Posts_update(title=req.get('title'), slug=slugify(req.get('title')), content=req.get('content'), mobile=req.get('mobile'))
post.save()
messages.success(request, 'The record was saved successfully')
return redirect('/')
else:
post = Posts.objects.get(id=post_id)
return render(request, 'update.html', {
'id': post.id,
'title': post.title,
'slug': post.slug,
'content': post.content,
'mobile': post.mobile
})
def read(request, post_mobile):
post = Posts_update.objects.get(mobile=post_mobile)
# post = Posts_update.objects.all()
return render(request, 'detail.html', {
'Posts_update': Posts_update
})
def delete(request, post_id):
post = Posts.objects.get(id=post_id)
post.delete()
messages.success(request, 'The record was deleted successfully')
return redirect('/')
detail.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Crud Django - {{ title }}</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
</head>
{% block content %}
<body>
<div class="container">
<div class="row">
<div class="col-sm-8 offset-sm-2">
<h2 class="display-6">Detail post</h2>
<div class="table-responsive">
<table class="table table-striped table-bordered">
<thead>
<tr>
<th scope="col">id</th>
<th scope="col">title</th>
<th scope="col">slug</th>
<th scope="col">content</th>
<th scope="col">Mobile</th>
</tr>
</thead>
<tbody>
{% if Posts_update %}
{% for post in Posts_update %}
<tr>
<td>{{ post.id }}</td>
<td>{{ post.title }}</td>
<td>{{ post.slug }}</td>
<td>{{ post.content }}</td>
<td>{{ post.mobile }}</td>
{% endfor %}
{% else %}
<tr>
<td colspan="5">No records found</td>
</tr>
{% endif %}
</tbody>
</table>
</div>
Back
</div>
</div>
</div>
</body>
{% endblock %}
</html>
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Crud Django</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-sm-12">
<h2 class="display-6">All Posts</h2>
Create post
{% if messages %}
{% for message in messages %}
<div class="alert alert-success mt-3 alert-dismissible fade show">
{{ message }}
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
{% endfor %}
{% endif %}
<div class="table-responsive mt-3">
<table class="table table-striped table-bordered">
<thead>
<tr>
<th scope="col">id</th>
<th scope="col">title</th>
<th scope="col">slug</th>
<th scope="col">content</th>
<th scope="col">Mobile</th>
<th scope="col">action</th>
</tr>
</thead>
<tbody>
{% if posts %}
{% for post in posts %}
<tr>
<td>{{ post.id }}</td>
<td>{{ post.title }}</td>
<td>{{ post.slug }}</td>
<td>{{ post.content }}</td>
<td>{{ post.mobile }}</td>
<th>
Delete
Detail
Update
</th>
</tr>
{% endfor %}
{% else %}
<tr>
<td colspan="5">No records found</td>
</tr>
{% endif %}
</tbody>
</table>
</div>
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js" integrity="sha512-bLT0Qm9VnAYZDflyKcBaQ2gg0hSYNQrJ8RilYldYQ1FxQYoCLtUjuuRuZo+fjqhx/qtq/1itJ0C2ejDxltZVFg==" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/#popperjs/core#2.5.4/dist/umd/popper.min.js" integrity="sha384-q2kxQ16AaE6UbzuKqyBE9/u/KzioAlnx2maXQHiDX9d4/zp8Ok3f+M7DPm+Ib6IU" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/js/bootstrap.min.js" integrity="sha384-pQQkAEnwaBkjpqZ8RU1fF1AKtTcHJwFl3pblpTlHXybJjHpMYo79HY3hIi4NKxyj" crossorigin="anonymous"></script>
</body>
</html>
In detail.html you are iterating over context object Posts_update
{% for post in Posts_update %}
Which is just Posts_update model, due to views.py.
I guess you meant the post variable there.

Problems with edit button in Django

i'm novice and just trying Django functionality. I create button to edit value in db in Django, but it doesn't work write. Problem in that: when i press the button (from notes.html), it's redirect to page edit_note.html, but values in fields is empty. When i manually press adress in browser, it work's normally. I don't understand where i maked mistake.
in views.py:
class EditNoteView(UpdateView):
model = Notes
form_class = NotesForm
template_name = 'notes/edit_notes.html'
context_object_name = 'note'
def get_success_url(self):
return reverse_lazy('edit_note', kwargs={'pk': self.object.pk})
in urls.py:
urlpatterns = [
path('', home, name='home'),
path('notes/', NoteView.as_view(), name='notes'),
path('<int:pk>/edit', EditNoteView.as_view(), name='edit_note'),
in notes.html:
{% for i in all_notes %}
<tr>
<td>{{ i.notes_category }}</td>
<td>{{ i.title }}</td>
<td>{{ i.text }}</td>
<td>{{ i.reminder_data_time }}</td>
<td>
<form action="{% url 'edit_note' i.id %}" method="post">
{% csrf_token %}
<div class="btn-small-group">
<button type="submit">Edit</button>
</div>
</form>
</td>
<td>
<div class="btn-small-group">
<button type="submit">Delete</button>
</div>
</td>
{% endfor %}
in edit_notes.html:
<form action="{% url 'edit_note' note.id %}" method="post">
{% csrf_token %}
{{ form.as_p }}
<div class="btn-small-group">
<button type="submit">Edit</button>
</div>
</form>
after press in notes.html on button "edit"
enter press adress in browser
The problem is the method you are using to access the edit form.
You are using the POST method instead of a GET method.
This make Django want to save the edited object instead of displaying the edit form. You should get some validation errors.
Solution
Change the request method to a GET method
Or use an anchor tag as below
Edit

Why does it show TypeError: UpdateContent() got an unexpected keyword argument 'instance'?

Working on a simple project in Django 3.2 and trying to add an edit button, to edit the content of the page. To do that I did:
views.py
def UpdateContent(request, pk):
contents = todo.objects.get(id=pk)
form = UpdateContent(instance=contents)
if request.method == 'POST':
form = UpdateContent(request.POST, instance=contents)
if form.is_valid():
form.save()
return redirect('/')
context = {'form': form}
return render(request, 'html/update.html', context)
forms.py
class UpdateContent(ModelForm):
class Meta:
model = todo
fields = ['content']
home.html
<table class="table table-dark table-hover table-bordered">
<thead>
<tr id="tr-table">
<th id="text-left">#</th>
<th id="text-center">ITEMS</th>
<th id="text-right"><i class="material-icons"></i></th>
</tr>
</thead>
<tbody>
{% for all_item in all_items%}
<tr>
<th id="row" scope="row"> {{ forloop.counter }} </th>
<td id="content">{{ all_item.content }}</td>
<form action="delete_todo/{{all_item.id}}/" method="post">
{% csrf_token %}
<td class="text-right-delete">
<button id="btn-delete" class="btn btn-outline-danger">Delete</button>
</td>
</form>
<td><a class="btn btn-outline-info" href="{% url 'todo:update' all_item.id %}">Edit</a></td>
</tr>
{% endfor %}
</tbody>
</table>
update.html
{% extends 'html/main.html' %}
{% load static %}
{% block content %}
<form action="", method="POST">
{% csrf_token %}
{{form}}
<input type="submit" name="Submit">
</form>
{% endblock %}
But when I run the code it shows me this error TypeError: UpdateContent() got an unexpected keyword argument 'instance'
Would appreciate any response or suggestion.
Thanks!
This is because your form and view have same names. So the view itself getting called recursively.
def UpdateContent(request, pk):
contents = todo.objects.get(id=pk)
form = UpdateContent(instance=contents)
if request.method == 'POST':
form = UpdateContent(request.POST, instance=contents)
if form.is_valid():
form.save()
return redirect('/')
context = {'form': form}
return render(request, 'html/update.html', context)

How to send data from CBV form to a template CBV?

I'm trying to send the POST data from a CBV form to other CBV.
I use the valid_form method to get the info by form.cleaned_data and then i apply in this method some custom methods.
But I cant send the result to the other view.
Also I tried put an action in the html sending to the other template and then grab the data but I cant.
views.py
from django.shortcuts import render
from django.views.generic.edit import FormView
from django.views.generic.base import TemplateView
from .forms import QuoteForm
from .models import SmgQuotesTable
from .quotes import Quotes
class QuoteFormView(FormView):
template_name = 'core/home.html'
form_class = QuoteForm
success_url = 'quotes'
def form_valid(self, form):
name = form.cleaned_data['name']
email = form.cleaned_data['email']
couple = form.cleaned_data['couple']
age = form.cleaned_data['age']
kids = form.cleaned_data['kids']
#query_filter = Quotes().planSelector(couple, kids, age)
#obj = SmgQuotesTable.objects.filter(composite='Ind. Junior (H25)')
return super(QuoteFormView, self).form_valid(form)
class QuoteListView(ListView):
model = SmgQuotesTable
def get_queryset(self):
queryset = super(QuoteListView, self).get_queryset()
queryset = queryset #
print(queryset)
return queryset
home.html
{% block content %}
<style>label{display:none}</style>
<form method="post" action="{% url 'quotes-list' %}">{% csrf_token %}
{{ form.as_p }}
<input type="submit" class="btn btn-primary btn-block py-2" value="Cotizar">
</form>
{% endblock %}
urls.py
from django.urls import path
from .views import QuoteFormView, QuoteListView
urlpatterns = [
path('', QuoteFormView.as_view(), name='home'),
path('quotes/', QuoteListView.as_view(), name='quotes-list'),
]
I expect to grab the name, email, couple, age and kids values in the QuoteView and apply the Quotes method so i can print the result in the quotes.html
I solve it.
In views.py replace the form_Valid method in the form view with the get_query method in the ListView.
With the self.request.GET() I get the info and pase it to the custom quot method.
Then i return the filtered information with the result.
from django.shortcuts import render
from django.views.generic.edit import FormView
from django.views.generic.list import ListView
from .forms import QuoteForm
from .models import SmgQuotesTable
from .quotes import Quotes
class QuoteFormView(FormView):
template_name = 'core/home.html'
form_class = QuoteForm
success_url = 'quotes'
class QuoteListView(ListView):
model = SmgQuotesTable
def get_queryset(self):
r_get = self.request.GET
d_get = {'name': None , 'email':None , 'couple': None, 'age': None, 'kids':None ,}
for value in d_get:
d_get[value] = r_get[value]
query_filter = Quotes().planSelector(d_get['couple'], d_get['kids'], d_get['age'])
queryset = super(QuoteListView, self).get_queryset().filter(composite=query_filter)
return queryset
In home.html have to change the POST method to a GET method, because the list view dont allow POST.
Adding in the the action to the ListView template I send the data in the form to takeit with the self.request.GET in the get_queryset() method.
{% extends 'core/base.html' %}
{% block title %}Cotizador{% endblock %}
{% load static %}
{% block headers %}
<h1>Cotizador</h1>
<span class="subheading">Cotiza tu plan!</span>
{% endblock %}
{% block content %}
<style>label{display:none}</style>
<form method="get" action="{% url 'quotes-list' %}">{% csrf_token %}
{{ form.as_p }}
<input type="submit" class="btn btn-primary btn-block py-2" value="Cotizar">
</form>
{% endblock %}
Finaly i put the information in the smgquotestable_list using the object_list and the properties of the model.
{% extends 'core/base.html' %}
{% block title %}Cotización{% endblock %}
{% load static %}
{% block headers %}
<h1>Cotización</h1>
<span class="subheading">Cotización</span>
{% endblock %}
{% block content %}
{% for item in object_list %}
<div class="table-responsive text-nowrap"></div>
<table class="table table-striped">
<thead>
<tr>
<th scope="col"></th>
<th scope="col">SMG01</th>
<th scope="col">SMG02</th>
<th scope="col">SMG10</th>
<th scope="col">SMG20</th>
<th scope="col">SMG30</th>
<th scope="col">SMG40</th>
<th scope="col">SMG50</th>
<th scope="col">SMG60</th>
<th scope="col">SMG70</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">{{ item.composite }}</th>
<td>$ {{ item.smg01 }}</td>
<td>$ {{ item.smg02 }}</td>
<td>$ {{ item.smg10 }}</td>
<td>$ {{ item.smg20 }}</td>
<td>$ {{ item.smg30 }}</td>
<td>$ {{ item.smg40 }}</td>
<td>$ {{ item.smg50 }}</td>
<td>$ {{ item.smg60 }}</td>
<td>$ {{ item.smg70 }}</td>
</tr>
</tbody>
</table>
</div>
{% endfor %}
{% endblock %}

Reading Checkbox in Django

This is NOT just another Reading Django Checkbox. I've read through 7 different posts about Checkbox on here along with 4 other pages in Django Documentation. My situation is a bit different. I can't read whether a specific checkbox is checked or not. I just get a value "True" for both checkboxes even when only one checkbox is checked. If nothing is checked, it worked as expected. Do I really need to use the MultipleChoiceField?
Current Output:
- John Doe Location A True ===> Checked
- James Smith Location A True ===> Unchecked
Ideally, I would like a list of dictionary that contains
data [0] = {'John', 'Doe', 1}
data [1] = {'John', 'Smith', 0}
...
where '1' is the flag for overwrite and '0' is to ignore.
Background:
User submits a form
Second form displays the previous information with checkbox next to the names if duplicates are found. If they're not duplicate, no checkbox will appear.
Read in the checkbox, process, and display the final page.
forms.py
from django import forms
from django.forms.formsets import BaseFormSet
class NameForm (forms.Form):
first_name = forms.CharField (max_length = 20, required = False)
last_name = forms.CharField (max_length = 20, required = False)
class BaseNameFormSet (BaseFormSet):
...
class CheckBox (forms.Form):
overwrite = forms.BooleanField (required = False)
views.py
def addname (request):
....
if request.method == 'POST':
....
if formset.is_valid ():
location = request.POST ['site']
data = formset.cleaned_data
# Store data into session to be used in another method
request.session ['location'] = location
request.session ['data'] = data
def process (request):
location = request.session ['location']
data = request.session ['data']
if request.method == 'POST':
form = CheckBox (request.POST)
if form.is_valid ():
overwrite = form.cleaned_data.get ('overwrite')
# for duplicate in checkboxes:
# overwrite = duplicate.get ('overwrite')
print (overwrite)
context = {'data': data, 'location': location, 'overwrite': overwrite}
return render (request, 'nodeform/success.html', context)
return HttpResponse ('No Overwrite Data.')
response.html
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
{% load staticfiles %}
<link rel="stylesheet" type="text/css" href="{% static 'nameform/style.css' %}" >
<title>Submitted Entries</title>
</head>
<body>
<h1>Submitted Entries:</h1>
<h4>Location: {{ location }}</h4>
<form action="process" method="POST">{% csrf_token %}
<div id="tablefont">
<table id="table01">
<tr>
<th>First Name</th>
<th>Last Name</th>
<th class="center">Overwrite</th>
</tr>
{% for info in data %}
<tr>
<td>{{ info.first_name }}</td>
<td>{{ info.last_name }}</td>
<td class="center"><input type="checkbox" name='overwrite-{{ forloop.counter0 }}'></td> ===> Testing Checkbox
<!--
{% if info.overwrite %}
<td class="center"><input type="checkbox" name='overwrite-{{ forloop.counter0 }}'></td>
{% else %}
<td class="center"></td>
{% endif %}
-->
</tr>
{% endfor %}
</table>
</div>
<br>
{% if errors %}
<p class="errorlh">Error:
<ul>
{% for error in errors %}
<li>{{ error }}</li>
{% endfor %}
</ul>
</p>
{% endif %}
<br>
<p><input type="submit" value="Confirm">
<a href="{% url 'addname' %}">
<button type="button">Cancel</button></a></p>
</form>
</body>
</html>
success.html
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Successfully Added</title>
</head>
<body>
<h1>Information captured:</h1>
<ul>
{% for info in data %}
<li>{{ info.first_name }} {{ info.last_name }} {{ location }} {{ overwrite }}</li>
{% endfor %}
</ul>
Add more names
</body>
</html>
All your checkbox inputs have the same attribute name=overwrite so, when you check one, it will be the only one submitted in the POST overwrite=true.
You should give an unique name to each input. I suggest you to use {{ forloop.counter0 }}, it will provide the current iteration of the loop, starting from 0. Basically it is the index of the current "info" in "data".
{% for info in data %}
<tr>
<td>{{ info.first_name }}</td>
<td>{{ info.last_name }}</td>
<td class="center"><input type="checkbox" name='overwrite-{{ forloop.counter0 }}'></td> ===> Testing Checkbox
<!--
{% if info.overwrite %}
<td class="center"><input type="checkbox" name='overwrite' value="1"></td>
{% else %}
<td class="center"></td>
{% endif %}
-->
</tr>
{% endfor %}
This way, you can match the form field in POST to the "info" in the backend.

Categories