Delete multiple rows in django - django

I am trying to delete severals rows at the same time in django.
How can I simply change the state of the booleanfield 'to_delete', just by clicking on the checkbox?
I am using datatables. The way how I am doing it is to create a boolean to_delete in my model, when the checkbox is selected, I am calling the function delete_multiple_company in my view. However, this doesn`t work. Any idea, what I am doing wrong please. Many Thanks,
I`ve created my view:
views.py
def delete_multiple_company(request, company_id):
company = get_object_or_404(Company, pk=company_id)
company = Company.objects.get(pk=company_id)
company.objects.filter(to_delete=True).delete()
return HttpResponseRedirect(reverse("company:index_company"))
urls.py
url(r'^(?P<company_id>[0-9]+)/delete_multiple_company/$', views.delete_multiple_company, name='delete_multiple_company'),
models.py
class Company(models.Model):
to_delete = models.BooleanField(default=False)
index.html
<span class="fa fa-plus"></span>Delete Companies
<table id="dtBasicExample" class="table table-striped table-hover">
<thead>
<tr>
<th>Select</th>
<th>#</th>
<th>Checked ?</th>
</tr>
</thead>
<tbody>
{% for company in companys.all %}
<tr>
<td id="{{ company.id }}"><input type="checkbox" class="companyCheckbox" name="checkedbox" id="{{ company.id }}" value="{{ company.id }}"></td>
<td>{{ company.id }}</td>
<td>{{ company.to_delete }}</td>
</tr>
{% endfor %}
</tbody>
</table>

I experienced a similar issue as you, what I did was put in a form.
index.py
<form method="POST" class="post-form">{% csrf_token %}
<button type="submit" class="save btn btn-default">Delete</button>
<span class="fa fa-plus"></span>Delete Companies</a>
<table id="dtBasicExample" class="table table-striped table-hover">
<thead>
<tr>
<th>Select</th>
<th>#</th>
<th>Checked ?</th>
</tr>
</thead>
<tbody>
{% for company in companys.all %}
<tr>
<td id="{{ company.id }}"><input type="checkbox" class="companyCheckbox" name="checkedbox" id="{{ company.id }}" value="{{ company.id }}"></td>
<td>{{ company.id }}</td>
<td>{{ company.to_delete }}</td>
</tr>
{% endfor %}
</tbody>
</table>
<button type="submit" class="save btn btn-default">Delete</button>
</form>
Clicking on the button then triggered the POST method in my view.
views.py
def index(request):
if request.method == 'POST':
print('I made it here')
# Put your code here, note you will return a dict, so some trial and error should be expected

Related

How to update database value in django on a button click

I have a template that contains one search button (this is for filtering the details based on option choose in the select) and a Next button (this is to move to next tab).
When the template loads for then i will search for projects from the select list and the result will be displayed in a table - which is working for me.
After the result is displayed in the table, i will select a row (through radio button) from that table and click on Next button to move to next tab. Here when i click the Next button i want to update some values in the django database but not able to achieve this. Can some one help me?
My View:
def form(request):
projects = CreateProjects.objects.filter(Status=True)
if request.method == 'POST':
selectproject = request.POST.get('selectproject')
searchprojlist = ListProjDetails.objects.filter(Project=selectproject)
return render(request,'form.html',{'projects':projects,'lists': searchprojlist})
elif request.POST.get('tab1btn','') == 'nxttab':
selval = ListProjDetails.objects.get(id=1)
selval.Selected = True
selval.LockedUser = request.user
selval.save()
else:
lists = ListProjDetails.objects.all()
return render(request,'form.html',{'projects':projects})
First If POST is working correctly, trouble is with the 2nd IF (2nd button). I have swapped the 2nd IF to be called fresh after the else statement but not working either.
I have passed id=1 for testing purpose only
enter image description here
I have added the image for better understanding, basically when the template loads select project from the list and Search and then choose one from the output and press next that moves to next tab by updating values like select to True and Locked User to current user.
My view as explained before.
My Javascript:
$(function(){
$('#nexttab').click(function(e){
e.preventDefault();
if(document.getElementById('selectradio').checked){
$('#tabs a[href="#tab2"]').tab('show');
}
});
})
Template:
<form method="POST">
{% csrf_token %}
<div class="row ml-auto">
<select class="custom-select mb-4 ml-2" name="selectproject" style="width: 30em;">
<option selected>Choose...</option>
{% for projects in projects %}
<option>{{ projects.ProjName}}</option>
{% endfor %}
</select>
<div class="ml-4">
<button type="submit" class="btn btn-primary" value="Search">Search</button>
</div>
</div>
<table class="table">
<thead class="thead-light">
<tr>
<th scope="col" class="text-center">S.No.</th>
<th scope="col" class="text-center">Project Name</th>
<th scope="col" class="text-center">Doc</th>
<th scope="col" class="text-center">Target Date</th>
<th scope="col" class="text-center">Docnum</th>
<th scope="col" class="text-center">Type</th>
<th scope="col" class="text-center">Select</th>
<th scope="col" class="text-center">Locked by User</th>
<th scope="col" class="text-center">Status</th>
</tr>
</thead>
<tbody>
{% for lists in lists %}
<tr>
<th scope="row" class="text-center">{{ lists.id }}</th>
<td class="text-center">{{ lists.Project }}</td>
<td class="text-center">{{ lists.doc }}</td>
<td class="text-center">{{ lists.TargetDate }}</td>
<td class="text-center">{{ lists.docnum }}</td>
<td class="text-center">{{ lists.type }}</td>
<td class="text-center"><input class="form-check-input" type="radio"
name="select1" id="selectradio" value="option1"></td>
<td class="text-center">{{ lists.LockedUser }}</td>
<td class="text-center">
{% if lists.DStatus == "Available" %}
<label class="badge badge-success">
{% else %}
<label class="badge badge-warning">
{% endif %}
{{ lists.DStatus }}</td>
</tr>
{% endfor %}
</tbody>
</table>
<div class="text-right mr-5">
<button type="submit" class="btn btn-primary" id="nexttab" name="tab1btn"
value="nxttab">Next</button>
</div>
</form>
I am just trying to re-factor your code, you should be able to pickup then.
from django.shortcuts import render, redirect
from django.urls import reverse
def form(request):
projects = CreateProjects.objects.filter(Status=True)
if request.method == 'POST':
if request.POST.get('tab1btn','') == 'nxttab':
selval = ListProjDetails.objects.get(id=1)
selval.Selected = True
selval.LockedUser = request.user
selval.save()
return redirect(reverse('name-of-the-view')) # redirect to form.html
selectproject = request.POST.get('selectproject')
searchprojlist = ListProjDetails.objects.filter(Project=selectproject)
return render(request,'form.html',{'projects':projects,'lists': searchprojlist})
else:
lists = ListProjDetails.objects.all()
return render(request,'form.html',{'projects':projects})

How to resolve "jinja2.exceptions.UndefinedError: 'nutrition' is undefined" error in Flask for CS50 Final Project

I am getting following error when i run the flask: jinja2.exceptions.UndefinedError: 'nutrition' is undefined. I tried several things but still couldn't resolve it.
Please help resolve the problem.
Code is below:
#app.route("/", methods=["GET", "POST"])
def index():
if request.method == "POST":
nutrition = Recipe_nutrition(request.form.get("recipes"))
instructions = Instructions(request.form.get("recipes"))
return render_template("index.html", nutrition = nutrition, instructions = instructions)
# User reached route via GET (as by clicking a link or via redi)
else:
return render_template("index.html")
{% extends "layout.html" %}
{% block title %}
Index
{% endblock %}
{% block main %}
<form action="/" method="post">
<div class="form-group">
<input autocomplete="off" autofocus class="form-control" name="recipes" placeholder="Recipe" type="text" required/>
</div>
<button class="btn btn-primary" type="submit">Search</button>
</form>
<table class="table table-striped" style="width:100%">
<tr>
<th>Nutrition</th>
<th>Amount</th>
<th>Units</th>
</tr>
{% for keys, values in nutrition.items() %}
<tr>
<td>{{ keys }}</td>
<td>{{ values[0] }}</td>
<td>{{ values[1] }}</td>
</tr>
{% endfor %}
</table>
<table class="table table-striped" style="width:100%">
<tr>
<th>#</th>
<th>Steps</th>
</tr>
{% for keys, values in instructions.items() %}
<tr>
<td>{{ keys }}</td>
<td>{{ values }}</td>
</tr>
{% endfor %}
</table>
{% endblock %}
In your Jinja template, you both access nutrition and instructions, but you only set them in case of a POST request.
You have several options now.
Either set both to an empty list, and also pass them into your render_template function for the GET case (your elsebranch).
Or return a different template, where nutrition and instructions are not necessary.
Maybe there is also a builtin Jinja solution, but I do not know one.

django checkbox get checkbox value from html

html file
<form method="post">
{% csrf_token %}
<table border="2" bordercolor="black" width="500" height="100" cellspacing="0" cellpadding="5">
<thead>
<tr>
<th>selection</th>
<th>student name</th>
<th>e-mail</th>
<th>CV</th>
</tr>
</thead>
<tbody>
{% for ta in tas %}
<tr>
<td><input type="checkbox" name="checkbox_list" value="{{ ta.id }}"></td>
<td>{{ ta.user.first_name }} {{ ta.user.last_name }}</td>
<td>{{ ta.user.email }}</td>
<td>view cv</td>
</tr>
{% endfor %}
</tbody>
</table>
<button type="submit">next</button>
</form>
views.py
def ta_ranking(request, id):
print('hello word!')
check_box_list = request.POST.getlist('checkbox_list')
if check_box_list:
print(check_box_list)
potential_ta = TA.objects.filter(id__in=check_box_list)
return render(request, 'ta_ranking.html', {'potential_ta': potential_ta, 'course_id': id})
return redirect('ta_list', id=id)
my question is that the ta_ranking class in views.py didn't be called when I click the submit button in html. How can I fix this problem?
Thanks for any help!
You didn't include the path to the view in your form:
<form method="POST" action="/path/to/ta_ranking">
...
</form>
You also need to add it to your urls.py if you haven't already:
from django.urls import path
from myapp.views import ta_ranking
urlpatterns = [
path('/path/to/ta_ranking', ta_ranking),
]

How to display 2 queryset list Frond end?(Django ListView get_queryset)

I got 2 queryset list expired_item and queryset in Django ListView, but I don't know when item is expired(queryset is empty), how to display another list expired_item on frond end, no matter what I changed in abc.html, expired_item won't dispaly, I pasted my code as below:
class ABCListView(ListView):
model = ABC
ordering = ('name', 'skill_course')
context_object_name = 'abcs'
template_name = ''
def get_queryset(self, **kwargs):
# Omitted
......
......
# Omitted
expired_item = list(ABC.objects.filter(pk__in=aa).exclude(pk__in=z))
queryset = Permit.objects.filter(pk__in=z)
return queryset
And my html file of abc.html as below:
{% extends 'base.html' %}
{% block content %}
<nav aria-label="breadcrumb">
</nav>
<h2 class="mb-3">My Items list</h2>
<div class="card">
<table class="table mb-0">
<thead>
<tr>
<th>Name</th>
<th>Department</th>
<th>Status</th>
<th></th>
</tr>
</thead>
<tbody>
{% for a in abcs %}
<tr>
<td class="align-middle">{{ a.name }}</td>
<td class="align-middle">{{ a.department.get_html_badge }}</td>
<td class="align-middle badge badge-pill badge-danger">{{ a.status }}</td>
</tr>
{% empty %}
{% endfor %}
</tbody>
</table>
</div>
<h2 class="mb-3">My Expired Items list</h2>
<div class="card">
<table class="table mb-0">
<thead>
<tr>
<th>Name</th>
<th>Department</th>
<th>Status</th>
<th></th>
</tr>
</thead>
<tbody>
{% for b in expired_item %}
<tr>
<td class="align-middle">{{ b.name }}</td>
<td class="align-middle">{{ b.department.get_html_badge }}</td>
<td class="align-middle badge badge-pill badge-danger">{{ a.status }}</td>
</tr>
{% empty %}
{% endfor %}
</tbody>
</table>
</div>
<div class="card-footer">
{% endblock %}
Thanks so much for any advice!
I would suggest use a normal django view. This Generic ListView is just created for the use of one list. Just pass both querysets in your context and render your template with that.
You could also use get_context_data() but this would be more or less hacky and not the qay I would recommend.

Toggle Checkbox in Django and Write to Database

I have some model
from django.db import models
class Model1(models.Model):
title = models.CharField(max_length=300)
boolean1 = models.BooleanField(default=False)
boolean2 = models.BooleanField(default=False)
and am currently displaying all database entries in a template via the following bootstrap table:
<div class = 'table-responsive'>
<table class='table table-striped'>
<thead>
<th>Title</th>
<th>Boolean 1</th>
<th>Boolean 2</th>
</thead>
{% if model1_list %}
{% for Model1 in model1_list %}
<tbody>
<tr>
<td>{{ Model1.title }}</td>
<td>{{ Model1.boolean1 }}</td>
<td>{{ Model1.boolean2 }}</td>
</tr>
{% endif %}
{% endfor %}
</tbody>
</table>
</div>
I'd like to display the boolean values as checkboxes rather than text, and to be able to check and uncheck the values and have it be reflected in the database (i.e., if the database is checked, the value should be True).
What would be a way to implement this?
Just use IF's:
<div class = 'table-responsive'>
<table class='table table-striped'>
<thead>
<th>Title</th>
<th>Boolean 1</th>
<th>Boolean 2</th>
</thead>
{% if model1_list %}
{% for Model1 in model1_list %}
<tbody>
<tr>
<td>{{ Model1.title }}</td>
<td>
<div class="checkbox">
<label><input type="checkbox" {% if Model1.boolean1 %} checked {% endif %}>Boolean 1</label>
</div>
</td>
<td>
<div class="checkbox">
<label><input type="checkbox" {% if Model1.boolean2 %} checked {% endif %}>Boolean 2</label>
</div>
</td>
</tr>
{% endif %}
{% endfor %}
</tbody>
</table>
</div>
When the user clicks, you want to send this information to the DB without refreshing the page? If yes, you need to do an ajax request to set this information to DB using JSON.Something like that:
$.ajaxFunction = function(){
var boolean1 = $("#boolean1").val(),
boolean2 = $("#boolean2").val(),
csrf_token = $("#csrf_token").val();
data_send = {
"boolean1": boolean1,
"boolean2": boolean2,
"csrfmiddlewaretoken": csrf_token
};
//jquery
$.ajax({
type: "post",
url: $("/url/ajax/").val(),
data: data_send,
success: function(data_receive){
if(data['boolean1']==true){
...
}
...
}
});
}
If no, you can just do a to POST this information and refresh the page!