Python Django tables with checkbox delete option - python

I am new to Django and currently trying to display a table with a checkbox which displays the list of records from the database and would have a delete button to delete multiple records using checkbox.
How to display a table with checkbox and delete button?
Appreciate your help!
Here is my code related to it:
models.py
class Customer(TimeStamp):
name = models.CharField(max_length=30, unique=True)
description = models.CharField(max_length=100,blank=True,help_text="Long-form name (optional)")
comments = models.TextField(blank=True)
class Meta:
ordering = ['-id']
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('App_CUS:customer_list')
views.py
class CustomerListView(ListView):
queryset = Customer.objects.order_by('id')
model = Customer
paginate_by = 10
context_object_name = 'customers'
template_name = 'App_CUS/customer_list.html'
customer_list.html
customer_list.html:
{% extends 'index.html' %}
{% load buttons %}
{% block content %}
<div class="pull-right">
{% if perms.App_CUS.customer_add %}
{% add_button 'App_CUS:customer_add' %}
{% delete_button 'App_CUS:customer_delete' %}
{% endif %}
</div>
<h1>{% block title %}Customers{% endblock %}</h1>
<div class="col-md-9">
<div class="table-responsive">
<table class="table table-hover table-headings table-bordered">
<thead>
<tr>
<th class="pk">
<input class="toggle" title="Toggle all" type="checkbox">
</th>
<th>ID</th>
<th>Customer Name</th>
<th>Description</th>
</tr>
</thead>
<tbody>
{% for customer in customers %}
<tr>
<th class="pk">
<input class="toggle" title="Toggle all" type="checkbox">
</th>
<td>{{ customer.pk }}</td>
<td>{{ customer.name }}</td>
<td>{{ customer.description }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>

I would add to your existing
{% for customer in customers %}
a new td tag including something like:
<td>
<div class="checkbox">
<input type="checkbox" name="name_check_{{customer.name}}" id="id_check{{customer.name}}" value="1"
{%if customer.data == 0 %}unchecked {%else%} checked {%endif%}>
</div>
<td>
I've used customer.data to represent a value stored in your db.
You could then write some js to do something on click of each new checkbox.
<script>
$(document).ready(function() {
$("#id_check_{{customer.id}}").on("click", function(){
#do something / ajax call etc..
OR
pass these values back to the view on form post (we've named each checkbox unique to the customer), then process the deletions from there.

Related

How I can get the value of check radio button in update page

How I can get the value of check radio button in update page, it save it DB but in update page it did not show the selected radio button.
in models
class UserListGroup(models.Model):
user_role = models.CharField(max_length=25, default="USER")
def __int__(self):
return self.ulg_id
class Meta:
db_table = 'userlist_group'
in add html
<tr>
<td class="mtrr"><b>User Role*</b></td>
<td class="mtrr"><label class="radio-inline"><input type="radio" name="user_role" value="admin" checked>Admin</label></td>
<td class="mtrr"><label class="radio-inline"><input type="radio" name="user_role" value="super">Super User</label></td>
<td class="mtt"><label class="radio-inline"><input type="radio" name="user_role" value="user">User</label></td>
</tr>
in update add html
<tr>
<td class="mtrr"><b>User Role*</b></td>
<td class="mtrr"><label class="radio-inline"><input {% if data.ul_role == True %} checked {% endif %} type="radio" name="user_role">Admin</label></td>
<td class="mtrr"><label class="radio-inline"><input {% if data.ul_role == True %} checked {% endif %} type="radio" name="user_role">Super User</label></td>
<td class="mtt"><label class="radio-inline"><input {% if data.ul_role == True %} checked {% endif %} type="radio" name="user_role">User</label></td>
</tr>
in view
def add_user(request):
if request.method == 'POST':
form = request.POST
user_role = form.get('user_role')
employee_master = UserListGroup.objects.create(user_role=user_role,
)//other code
Your information is a bit incomplete as you left out the update view
You can solve your problem as follows
Add CHOICE attribute to your user_role field
In model:
class UserListGroup(models.Model):
ROLE = (('user', 'USER'), ('admin', 'ADMIN'), ('super', 'SUPER USER'))
user_role = models.Charfield(max_length=25, choices=ROLES, default=user)
using choices will cause a html widget to be used, to use a radio button, create a Django form and update it as below
from Django forms import ModelForm, RadioSelect
from .models import UserListGroup
class UserListGroupForm(ModelForm):
class Meta:
model = UserListGroup
field = '__all__'
widgets = {
'user_role': RadioSelect()
}
Your add.html and update.html would look similar to
<form method="POST" action="">
{% csrf_token %}
{{ form }}
</form>
For such simple crude operation, you are better off using the Django generic view
On a final note, the approach you use in your update.html in checking for the current user role is wrong, as the condition is same in all three cases. It should be compared with their possible database values as follows
<tr>
<td class="mtrr"><b>User Role*</b></td>
<td class="mtrr"><label class="radio-inline"><input {% if data.ul_role == 'admin' %} checked {% endif %} type="radio" name="user_role">Admin</label></td>
<td class="mtrr"><label class="radio-inline"><input {% if data.ul_role == 'super' %} checked {% endif %} type="radio" name="user_role">Super User</label></td>
<td class="mtt"><label class="radio-inline"><input {% if data.ul_role == 'user' %} checked {% endif %} type="radio" name="user_role">User</label></td>
</tr>

Django User Posts filter by year

In Django I needed user Posts filter by year, so I did the following in views:
Views:
from django.contrib.auth.models import User
from django.db.models import Count
from .models import Book
def about (request):
model = Book
context = {
'books': Book.objects.values('author')
.filter(date_posted__year=2019)
.annotate(total_books = Count('author'))
}
In the HTML
books.author.id
books.author
books.total_books
It worked, it shows the total but instead of printing de Author username, it prints the Author ID, and the author ID is blank.
Django Version 3.0.8
This is the complete HTML:
{% block content %}
<div class="container">
<div class="w-50">
<table class="table">
<thead class="thead-dark">
<tr>
<th scope="col">User ID</th>
<th scope="col">Username </th>
<th scope="col">Total Books</th>
</tr>
</thead>
{% for books in books %}
<tbody>
<tr>
<ul>
<td> {{ books.author }}</td>
<td> {{ books.author }} </td>
<td>{{ books.total_qcreports}}</td>
</ul>
</tr>
</tbody>
{% endfor %}
</table>
</div>
</div>
{% endblock content %}
Models:
class Book(models.Model):
title = models.CharField(max_length=100)
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.title
This is how it shows in browser:
enter image description here
context = {
'books': Book.objects.values('author','author__username')
.filter(date_posted__year=2019)
.annotate(total_books = Count('author'))
}
HTML Template
{{book.author}}
{{book.author__username}}
{{book.total_book}}

How To Populate Table With Filtered Data in Django

I am attempting to populate a table with a filtered set of data from my Manifests model using a url parameter.
I believe that the problem I am having is in the Views.py line
manifests = Manifests.objects.all().filter(reference=reference_id)
Models.py
class Manifests(models.Model):
reference = models.ForeignKey(Orders)
cases = models.IntegerField()
description = models.CharField(max_length=1000)
count = models.IntegerField()
def __str__(self):
return self.description
Urls.py
url(r'^add_manifest/(?P<reference_id>\d+)/$', add_manifest, name='add_manifest'),
Views.py
def add_manifest(request, reference_id):
if request.method == "POST":
form = CreateManifestForm(request.POST)
if form.is_valid():
instance = form.save(commit=False)
try:
order = Orders.objects.get(id=reference_id)
except Orders.DoesNotExist:
pass
instance.reference = order
instance.save()
return redirect('add_manifest', reference_id=reference_id)
form = CreateManifestForm()
#manifests = Manifests.objects.all()
manifests = Manifests.objects.all().filter(reference=reference_id)
context = {
'form': form,
'reference_id': reference_id,
'manifests' : manifests,
}
return render(request, 'add_manifest.html', context)
template (add_manifest.html)
{% extends 'base.html' %}
{% block body %}
<div class="container">
<form method="POST">
<br>
<br>
<br>
{% csrf_token %}
<div class="column">
<label for="form.reference">Reference ID: </label><br>
<input type="text" value="{{ reference_id }}">
<br>
</div>
<div class="description">
<div class="column">
<label for="form.description">Description: </label>
<br>
{{ form.description}}
</div>
</div>
<div class="column">
<label for="form.cases">Cases: </label>
<br>
{{ form.cases }}
<br>
</div>
<div class="column">
<label for="form.count">Count: </label>
<br>
{{ form.count }}
<br>
<br>
</div>
<br>
<br>
<button type="submit" name="add_mani" style="border-color: #7395AE;">Add Line</button>
</form>
<br>
<h4>Manifest</h4>
<div class="table-responsive">
<table class="table table-striped table-bordered manifest_table" cellspacing="0" style="width="100%">
<thead>
<tr>
<th></th>
<th style="width:10%;">Ref ID</th>
<th style="width:10%;">Cases</th>
<th style="width:60%;">Description</th>
<th style="width:10%;">Count</th>
</tr>
</thead>
<tbody>
{% for manifests in manifests %}
<tr>
<td>
Edit
</td>
<td>{{ manifests.reference }}</td>
<td>{{ manifests.cases }}</td>
<td>{{ manifests.description}}</td>
<td>{{ manifests.count}}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<div class="text-center">
<button type="submit" class="btn btn-primary" name="button" align="right">Subit Manifest</button>
</div>
</div>
I want the table to display only lines where the reference in the Manifests model = the reference_id in the URL. Currently it does not work as such, the table is just empty.
Change the for-loop variable name like this:
{% for manifest in manifests %}
<tr>
<td>
Edit
</td>
<td>{{ manifest.reference }}</td>
<td>{{ manifest.cases }}</td>
<td>{{ manifest.description}}</td>
<td>{{ manifest.count}}</td>
</tr>
{% endfor %}
If there is any Manifest object for reference_id, then it will render them in template.
Update
Its possible that your form is not validating. So its a good idea to render form errors:
# view
def add_manifest(request, reference_id):
form = CreateManifestForm(request.POST or None)
if request.method == "POST":
if form.is_valid():
instance = form.save(commit=False)
try:
order = Orders.objects.get(id=reference_id)
instance.reference = order
except Orders.DoesNotExist:
pass
instance.save()
manifests = Manifests.objects.all().filter(reference=reference_id)
context = {
'form': form,
'reference_id': reference_id,
'manifests' : manifests,
}
return render(request, 'add_manifest.html', context)
And update template to show the errors in template as well:
{% if form.errors %}
{% for field in form %}
{% for error in field.errors %}
<div>
<strong>{{ error|escape }}</strong>
</div>
{% endfor %}
{% endfor %}
{% for error in form.non_field_errors %}
<div>
<strong>{{ error|escape }}</strong>
</div>
{% endfor %}
{% endif %}

Multiple variable to store on a column of database Flask

I'm working on an app for Transport Company and on the client page, we can add Delivery Tour and these Delivery Tours can be planned on different days and hours :
exemple :
A delivery tour is planned on Monday at 4pm and Thursday 10am.
Currently, I store this in my SQLAlchemy Delivery Tour database in JSON Format like this :
{'Monday':10,'Thursday':16}
But the thing is when I rendered the HTML file I can't success to iterate through the JSON file and have the correct day and hour associated to the correct Delivery Tour...
So I was wondering is there a more efficient way to do this ? Like maybe create a new table but I have no idea how to arrange columns.
EDIT
My HTML :
<div class="card">
<div class="card-header-spe">
<p style="text-align:left;">
Delivery Tour
<span style="float:right;">
<a class=" card-category btn btn-primary" href="{{ url_for('deliver', client_id=client.id )}}">Add New</a>
</span>
</p>
</div>
<table class="table table-striped table-hover">
<thead>
<tr>
<th scope="col">Title</th>
<th scope="col">Description</th>
<th scope="col">Schedule</th>
<th scope="col">Driver</th>
</tr>
</thead>
<tbody>
<tr>
{% for deliv in delivery %}
<th scope="row">{{ deliv.title }}</th>
<td>{{ deliv.description }}</td>
<td >{{ deliv.schedule }} </td>
{% if deliv.driver_assigned %}
{% for d in driver %}
{% if d.id == deliv.driver_assigned %}
<td>{{d.first_name}}</td>
{% endif %}
{% endfor %}
{% else %}
<td></td>
{% endif %}
</tr>
{% endfor %}
</tbody>
</table>
</div>
And here is a photo of my Delivery database :
You have the basics of it already:
{% for day, hour in eval(deliv.schedule).items() %}
You would have to do eval because unless I'm wrong, you have that column stored as a string in the table.
If it were me, I'd create a table just for the schedules and make a one-to-many relationship to your delivery_tour table: (note: drop the schedule column on your delivery_tour table)
class TourSchedule(Base):
__tablename__ = 'tour_schedules'
id = Column(Integer, primary_key=True)
tour_id = Column(Integer, ForeignKey('delivery_tour.id'))
tour = relationship('DeliveryTour', backref='schedule')
day = Column(String(16))
hour = Column(Integer)
Then you can just iterate over it like you otherwise would:
<td>
<ul style="list-style-type: none;">
{% for sched in deliv.schedule %}
<li>{{sched.day}}: {{sched.hour}}</li>
{% endfor %}
</ul>
</td>

Form fields not displayed in django html

I have written a code to make form , and i have no guess why the fields are not displayed here are my codes.
I want to get a request from the index.html page and using that request, I ran a query to display the results of the query on the same page.
views.py
def search123(request):
searc=search1()
if request.method=="POST":
searc=search1(request.POST or None)
if searc.is_valid():
if 'd_box' in request.POST:
item_map=item.objects.raw('SELECT * FROM `item` WHERE `category_id`=%s', [request.POST['d_box']])
lis=[]
for e in (item_map):
lis.append(e.id)
price_map=item_done.objects.filter(item_id__in=lis).order_by('item_id')
return render_to_response('index.html',{'posts':price_map},RequestContext(request))
return render_to_response('index.html',{'posts':searc},RequestContext(request))
index.html
<html>
<head>
</head>
<body>
<form method='POST' action=''>{% csrf_token %}
<h4> SEARCH </h4>
{{searc.as_table}}
<input type='submit' name="button7" value="button7">
</form>
{% regroup posts by item_id as post_list %}
<table border="4" style="width:1050px;border-collapse: collapse" >
<thead>
<tr>
<th>Item Codes</th>
<th>Name</th>
<th>MRP</th>
<th>Site price</th>
<th>Website</th>
</tr>
</thead>
<tbody>
{% for country in post_list %}
<tr>
<td>{{ country.grouper }}</td>
<td>
{% for item in country.list %}
<div style="margin: 5px 5px">{{item.name}}</div>
{% endfor %}
</td>
<td>
{% for item in country.list %}
<div style="margin: 5px 5px">{{item.mrp}}</div>
{% endfor %}
</td>
<td>
{% for item in country.list %}
<div style="margin: 5px 5px">{{item.site_price}}</div>
{% endfor %}
</td>
<td>
{% for item in country.list %}
<div style="margin: 5px 5px">{{item.crawl_id}}</div>
{% endfor %}
</td>
</tr>
{% endfor %}
</tbody>
</table>
</html>
forms.py
class search1(forms.ModelForm):
class Meta:
model=search
exclude=[]
i think you must import search model in forms.py an also in your template you write the form name wrong ! you write {{searc.as_table}} it must be {{search.as_table}}

Categories