Toggle Checkbox in Django and Write to Database - django

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!

Related

problem of django form in posting request

I'm working on a project and I made a form but when I submit sth it doesn't send it to database although in cmd it shows that request method is post.I really don'tkhow how to deal with it.
thats template code:
{%extends 'base.html'%}
{%block title%}
<title>projects</title>
{%endblock title%}
{%block content%}
<div class="container">
</br>
<form method="post">
{% csrf_token %}
<div class="form-group">
<input type="text" class="form-control" name="project" placeholder="new project?">
</div>
<button type="submit" class="btn btn-primary">add</button>
</form>
</br>
</br>
<table class="table">
<thead class="thead-dark">
<tr>
<th scope="col"> project-title</th>
<th scope="col">update</th>
<th scope="col">delete</th>
<th scope="col">divide</th>
</tr>
</thead>
<tbody>
{% for obj in all_projects %}
<tr>
<td>{{ obj.proTitle }}</td>
<td>{{ obj.done }}</td>
<td>Delete</td>
<td>Devide</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{%endblock content%}
any advise will be greatly appreciated:))
I solved it ;
in the input tag i put name="project" but the attribute that I defined in my model was "proTitle"
so when I chnged it the problem solved.

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.

Delete multiple rows in 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

How to persist data found in tables within a django template, in postgresql

I am scraping several sites and I show the data obtained in 6 tables within a django template.
My intention is to persist the data of the tables in postgresql, but I can not realize how to perform that task.
In principle I am trying to save the data from the second table.
For this I have created the models that I show below, as well as a view that is called: registroDivisaArgentina ().
The template is called quotes.html and within it, there are 6 tables.
I have tried to work with a class called: RegisterArgentineValues () within a forms.py file
models.py
class DivisasArgentina(models.Model):
class Meta:
ordering = ['CodigoDA']
CodigoDA = models.CharField(max_length=50, primary_key = True)
Texto_para_Reporte = models.CharField(max_length=70)
def __str__(self):
return '{}'.format(self.Texto_para_Reporte)
class ValoresDivisasArgentina(models.Model):
class Meta:
ordering = ['Dia']
DivisasArgentina = models.ForeignKey(DivisasArgentina, on_delete=models.PROTECT)
Dia = models.DateField(default=date.today)
Hora = models.DateTimeField(default=timezone.now)
Compra = models.FloatField()
Venta = models.FloatField()
Variacion_dia_anterior = models.FloatField()
ClaveComparacion = models.CharField(max_length=1)
def __str__(self):
return '{} - {} - {}'.format(self.DivisasArgentina, self.Dia, self.ClaveComparacion)
cotizaciones.html
{% extends 'base.html' %}
{% block contenido %}
<form method="POST" class="post-form">{% csrf_token %}
<div class="container">
<table class="table table-striped table-bordered" id="tab1">
<thead>
<tr>
<th>Divisas en el Mundo</th>
<th>Valor</th>
</tr>
</thead>
<tbody>
<tr>
{%for element in cotiz_mun%}
<tr>
{% for key,value in element.items %}
<td> {{ value }} </td>
{% endfor %}
</tr>
{% endfor %}
</tr>
</tbody>
</table>
</div>
<div class="container">
<table class="table table-striped table-bordered" id="tab2">
<thead>
<tr>
<th>Divisas en Argentina</th>
<th>Compra</th>
<th>Venta</th>
</tr>
</thead>
<tbody>
<tr>
{%for element in cotiz_arg%}
<tr>
{% for key,value in element.items %}
<td>{{ value }} </td>
{% endfor %}
</tr>
{% endfor %}
</tr>
</tbody>
<thead>
{{ form.as_table }}
</table>
</div>
<div class="container">
<table class="table table-striped table-bordered" id="tab3">
<thead>
<tr>
<th>Dolar Banco Nacion Argentina (Divisas)</th>
<th>Compra</th>
<th>Venta</th>
</tr>
</thead>
<tbody>
<tr>
{%for element in cotiz_exp%}
<tr>
{% for key,value in element.items %}
<td>{{ value }} </td>
{% endfor %}
</tr>
{% endfor %}
</tr>
</tbody>
</table>
<table class="table table-striped table-bordered" id="tab4">
<thead>
<tr>
<th colspan="4">Dolar Futuro en Argentina</th>
</tr>
<tr>
<th>Mes 1</th>
<th>Mes 2</th>
<th>Mes 3</th>
<th>Mes 4</th>
</tr>
</thead>
<tbody>
<tr>
{%for element in cotiz_dol%}
<td>
{{ element.Valores}}
</td>
{% endfor %}
</tr>
</tbody>
</table>
<table class="table table-striped table-bordered" id="tab5">
<thead>
<tr>
<th colspan="3">Indicadores Varios - Tasa Libor</th>
</tr>
<tr>
<th>Libor a 1 Mes</th>
<th>Libor a 2 Mes</th>
<th>Libor a 3 Mes</th>
</tr>
</thead>
<tbody>
<tr>
{%for element in cotiz_lib%}
<td>
{{ element.Valores }}
</td>
{% endfor %}
</tr>
</tbody>
</table>
<table class="table table-striped table-bordered" id="tab6">
<thead>
<tr>
<th>Indicadores Varios - Indice Merval y Oro</th>
<th>Valores</th>
</tr>
</thead>
<tbody>
<tr>
{%for element in cotiz_ind%}
<tr>
{% for key,value in element.items %}
<td> {{ value }} </td>
{% endfor %}
</tr>
{% endfor %}
</tr>
</tr>
</tbody>
</table>
</div>
<div class="container" id="saveData">
<br></br>
<button type="submit" class="btn btn-primary pull-right">Guardar Datos</button>
</div>
</form>
{% endblock %}
views.py
def mostrar_cotizaciones(request):
cotiz_arg = json.loads(j_cotizaciones_argentina)
cotiz_mun = json.loads(j_cotizaciones_mundiales)
cotiz_exp = json.loads(j_cotizacion_export)
cotiz_dol = json.loads(j_dolar_futuro)
cotiz_ind = json.loads(j_indicadores)
cotiz_lib = json.loads(j_libor)
context = {'cotiz_mun': cotiz_mun,
'cotiz_arg': cotiz_arg,
'cotiz_exp': cotiz_exp,
'cotiz_dol': cotiz_dol,
'cotiz_ind': cotiz_ind,
'cotiz_lib': cotiz_lib,
}
return render(request, 'cotizaciones.html', context)
def registrarDivisaArgentina(request):
if request.method == 'POST':
formulario = RegistrarValoresDivisasArgentinas(request.POST)
if formulario.is_valid():
formulario.save()
return HttpResponseRedirect('/listadoValores')
else:
formulario = RegistrarValoresDivisasArgentinas()
formulario.setup('Registrar', css_class="btn btn-success")
return render(request, 'cotizaciones.html', {'formulario':formulario})
forms.py
from django import fla
from django.forms import ModelForm
from django import forms
from fla.models import *
class RegistrarValoresDivisasArgentinas(forms.ModelForm):
class Meta:
model = ValoresDivisasArgentina
fields= [Compra, Venta]
I have done some tests, but none has given a favorable result. Someone can tell me how to process the data (in the views and forms) that are in the tables, to be able to store them in my postgres tables ?
I do this kind of task very often, and I've found out that the combination of ScraPy with scrapy-djangoitem is a very good combo to use here.
Good luck!

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.