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.
Related
I made CRUD in django. Update is not working while creating and deleting views are working.Please fix my problem.And tell me where i am lacking.
This is views.py:
from .import models
from django.http import HttpResponse,HttpResponseRedirect
from django.shortcuts import render
from .forms import readerRegistrationForm
from .models import Reader, books
from django.views.generic import TemplateView,RedirectView,UpdateView
from django.views import View
# Create your views here.
def done(request):
return render(request,'done.html')
class addshowView(TemplateView):
template_name='add&show.html'
def get_context_data(self,*args,**kwargs):
context= super().get_context_data(**kwargs)
fm=readerRegistrationForm()
stu=Reader.objects.all()
cone=books.objects.all()
context={'str':stu,'form':fm,'con':cone}
return context
def post(self,request):
fm=readerRegistrationForm(request.POST)
if fm.is_valid():
fm.save()
return HttpResponseRedirect('/')
class userdeleteview(RedirectView):
url='/'
def get_redirect_url(self, *args, **kwargs):
p=kwargs['id']
Reader.objects.get(pk=p).delete()
return super().get_redirect_url(*args, **kwargs)
class Updateview(UpdateView):
def get(self,request,id):
pi=Reader.objects.get(pk=id)
fm=readerRegistrationForm(instance=pi)
return render(request,'updateit.html',{'form':fm})
def post(self,request,id):
pi=Reader.objects.get(pk=id)
fm=readerRegistrationForm(request.POST,instance=pi)
if fm.is_valid():
fm.save()
return render(request,'updateit.html',{'form':fm})`
This is forms.py:
from django.forms import fields, widgets
from .models import books,Reader
class readerRegistrationForm(forms.ModelForm):
class Meta:
model=Reader
fields=['name','email','comment']
this is models.py:
from django.db.models.deletion import CASCADE
#Create your models here.
class books(models.Model):
name=models.CharField(max_length=200)
gener=models.CharField(max_length=200)
author=models.CharField(max_length=200)
isbn=models.BigIntegerField()
def __str__(self) :
return self.name
class Reader(models.Model):
name=models.CharField(max_length=200)
email=models.EmailField(max_length=200)
comment=models.TextField()
def __str__(self) :
return self.comment
This is urls.py:
from django.contrib import admin
from django.urls import path
from boom import views
urlpatterns = [
path('', views.addshowView.as_view() , name='show'),
path('updated/',views.done,name='done'),
path('delete/<int:id>/', views.userdeleteview.as_view() , name='doNow'),
path('update/<int:id>/', views.Updateview.as_view() , name='UpNow'),
path('admin/', admin.site.urls),
]
This is updateit.html
{% extends 'index.html' %}
{% block body_block %}
<div class="container">
<h1>Welcome to Reader Update Page!!</h1>
<form method="POST">
{% csrf_token %}
{{form.as_p}}
<button type="button" class="btn btn-success">Update</button>
</form>
</div>
{% endblock %}
this is index.html
<!DOCTYPE html>
{%load static%}
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Base</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
</head>
<body>
<div class="container">
<div class="alert alert-danger" role="alert">
<div class="blockquote text-center"><h1 class="alert">Welcome!!</h1>
<h1>This is My Virtual Book Stall!</h1>
</div>
</div>
<div class="jumbotron">
{% block body_block %}
{% endblock %}
</div>
</div>
</body>
</html>
This is add&show.html
{% extends 'index.html' %}
{% block body_block %}
<div style="text-align: center;">
<h1 class="alert alert-secondary" role="alert"><em>This is The Library U can Grab!!</em></h1>
<table class="table">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Author</th>
<th>Gener</th>
</tr>
</thead>
<tbody>
{% for st in con %}
<tr>
<th>{{st.id}}</th>
<td>{{st.name}}</td>
<td>{{st.author}}</td>
<td>{{st.gener}}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<form method="POST" class="table table-primary">
{% csrf_token %}
<div class="row justify-content-between">
<div class="col-4">
<h3 class="alert alert-secondary" role="alert">Add member</h3>
{{form.as_p}}
<input class="btn btn-primary" type="submit" value="Register">
</div>
<div class="col-8">
<h3 style="text-align: center;" class="alert alert-secondary" role="alert">Show Data</h3>
{% if str %}
<table class="table ">
<thead>
<tr>
<th scope="col">id</th>
<th scope="col"><strong>Name</strong> </th>
<th scope="col"><strong> Email</strong></th>
<th scope="col"><strong> Comment</strong></th>
<th scope="col"><strong> Action</strong></th>
</tr>
</thead>
<tbody>
{% for st in str %}
<tr>
<th scope="row">{{st.id}}</th>
<td>{{st.name}}</td>
<td>{{st.email}}</td>
<td>{{st.comment}}</td>
<td><button type="button" class="btn btn-success">Edit</button>
<button type="button" class="btn btn-danger">Delete</button></td>
</tr>
{% endfor %}
</tbody>
</table>
{% else %}
<h3>NO RECORDS NOW</h3>
{% endif %}
</div>
</div>
</form>
{% endblock %}
This is done.html
{% extends 'index.html' %}
{% block body_block %}
<div class="jumbotron">
<h3>Information updated Successfully!!</h3>
Click Me
</div>
{% endblock %}
You don't need to use two functions separately for update.
Use this:
class Updateview(UpdateView):
def update(request, pk):
pi=Reader.objects.get(pk=id)
fm = readerRegistrationForm(instance=pi)
if request.method == 'POST':
fm = readerRegistrationForm(request.POST, instance=pi)
if fm.is_valid:
fm.save()
return redirect('home')
context = {'form':fm}
return render(request,'updateit.html', context )
I am continuing the Inspections/Defects project that I am doing for fun. On line 29, the error says that HomeTests has no attribute Inspection, and I am trying to find out why.
Here is the tests.py file.
class HomeTests(TestCase):
def setUp(self):
Inspection.objects.create(workOrderNum='123DER', partNumber='sd', customerName="RYANTRONICS", qtyInspected=10,qtyRejected=3)
url = reverse('home')
self.response = self.client.get(url)
def test_home_view_status_code(self):
self.assertEquals(self.response.status_code, 200)
def test_home_url_resolves_home_view(self):
view = resolve('/')
self.assertEquals(view.func, home)
def test_home_url_resolves_home_view(self):
view = resolve('/')
self.assertEquals(view.func, home)
def test_home_view_contains_link_to_topics_page(self):
inspection_topics_url = reverse(inspection_topics, kwargs={'pk': self.inspection.pk}) -> error occurs at this line
self.assertContains(self.response, 'href="{0}"'.format(inspection_topics_url))
I also have been looking in my views.py file to see if it was the source of the problem. I followed the guide at Django URLs Advanced but I had missed something.
Here is the views.py file in case you wanted to look at it.
from django.shortcuts import render,get_object_or_404
from .models import Inspection
# Create your views here.
def home(request):
inspections = Inspection.objects.all()
return render(request, 'home.html', {'inspections': inspections})
def inspection_topics(request, pk):
inspection = get_object_or_404(Inspection, pk=pk)
return render(request, 'topics.html', {'inspection': inspection})
The views.py has two files, home.html and topics.html. Here they are.
{% load static %}<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Final Inspection Report</title>
<link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}">
</head>
<body>
<div class="container">
<ol class="breadcrumb my-4">
<li class="breadcrumb-item active">Final Inspection Report</li>
</ol>
<table class="table">
<thead class="thead-inverse">
<tr>
<th>Inspection</th>
<th>Customer Name</th>
<th>Quanity Inspected</th>
<th>Quantity Rejected</th>
</tr>
</thead>
<tbody>
{% for inspection in inspections %}
<tr>
<td>
{{ inspection.workOrderNum }}
<small class="text-muted d-block">{{ inspection.partNumber }}</small>
</td>
<td class="align-middle">{{ inspection.customerName }}</td>
<td class="align-middle">{{ inspection.qtyInspected }}</td>
<td class="align-middle">
{{ inspection.qtyRejected }}
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</body>
</html>
This is the home page where the inspections are stored.
And here is topics.html.
{% load static %}<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>{{ inspection.workOrderNum }}</title>
<link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}">
</head>
<body>
<div class="container">
<ol class="breadcrumb my-4">
<li class="breadcrumb-item">Inspections</li>
<li class="breadcrumb-item active">{{ inspection.workOrderNum }}</li>
</ol>
</div>
</body>
</html>
When I did this, the error I got was HomeTests has no attribute inspection, but the error that I should have gotten was False is not true: Couldn't find href=/inspections/1/. How do I fix the HomeTests has no attribute error?
Use this instead:
self.inspection = Inspection.objects.create(
workOrderNum='123DER',
partNumber='sd',
customerName='RYANTRONICS',
qtyInspected=10,
qtyRejected=3,
)
In general, for the tests.py, in the future:
self.[model] = [model].object.create(attributes_of_model)
where [model] is the name of your model class in the models.py file and attributes_of_model are the attribute(s) that model has.
I am writing a comment page with Django 1.11. I've already added {% csrf_token %} in my template but I still receive the error message
Forbidden (403) CSRF verification failed. Request aborted.
My code is as below:
from django.shortcuts import render_to_response
from restapp.models import Restaurant
from restapp.models import Food
from django.http import HttpResponseRedirect
from restapp.models import Restaurant
from django.utils import timezone
from django.template import RequestContext
def comment(request,id):
if id:
r = Restaurant.objects.get(id=id)
else:
return HttpResponseRedirect("/restaurants_list/")
if request.POST:
visitor = request.POST['visitor']
content = request.POST['content']
email = request.POST['email']
date_time = timezone.localtime(timezone())
Comment.objects.create(
visitor=visitor,
email=email,
content=content,
date_time=date_time,
restaurant=r
)
return render_to_response('comments.html', context=locals())
Here is my template:
<!doctype html>
<html>
<head>
<title>Comments</title>
<meta charset='utf-8'>
</head>
<body>
<h2>{{r.name}}的評價</h2>
{% if r.comment.all %}
<p>目前共有{{r.comment.all|length}}的評價</p>
<table>
<tr>
<th>留言者</th>
<th>時間</th>
<th>評價</th>
</tr>
{% for c in r.comment.all %}
<tr>
<td>{{c.visiter}}</td>
<td>{{c.date_time | date:"F j, Y"}}</td>
<td>{{c.content}}</td>
</tr>
{% endfor %}
</table>
{% else %}
<p>無評價</p>
{% endif %}
<br/ ><br/ >
<form action="" method="post">{% csrf_token %}
<table>
<tr>
<td><label for="visitor">留言者:</label></td>
<td><input id="visitor" type="text" name="visitor"></td>
</tr>
<tr>
<td><label for="email">電子信箱:</label></td>
<td><input id="email" type="text" name="email"></td>
</tr>
<tr>
<td><label for="content">評價:</label></td>
<td><textarea id="content" rows="10" cols="48" name="content"></textarea></td>
</tr>
</table>
<input type="submit" value="給予評價">
</form>
</body>
</html>
Use csrf_exempt if you are not bothered about csrf verification.
Refer the docs here.
https://docs.djangoproject.com/en/dev/ref/csrf/#django.views.decorators.csrf.csrf_exempt
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>
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.