django checkbox get checkbox value from html - django

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),
]

Related

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

MultiValueDictKeyError at /upload/

i need some help with Django, i keep encounter the MultiValueDictKeyError when i click the download button. And it shows MultiValueDictKeyError at /upload/
'my_file' but not sure how to solve it after several attempts. Below are my codes for models, view, and the template page. For your advice please.
files_ul_dl.html
<form method="post" enctype="multipart/form-data">{% csrf_token %}
<input type="file" name="my_file">
<button class="btn btn-secondary" type="submit">Upload</button>
</form>
</div>
<hr>
<h4>File Type Count</h4>
<table class="table">
<thead>
<tr>
{% for file_type in file_types %}
<th scope="col">{{ file_type }}</th>
{% endfor %}
</tr>
</thead>
<tbody>
<tr>
{% for file_type_count in file_type_counts %}
<td>{{ file_type_count }}</td>
{% endfor %}
</tr>
</tbody>
</table>
<br/>
<h4>Files</h4>
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">file name</th>
<th scope="col">size</th>
<th scope="col">file type</th>
<th scope="col">upload date</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
{% for file in files %}
{% url 'files_upload:download_file' as download_file_url%}
<tr>
<th scope="row">{{ forloop.counter }}</th>
<td>{{ file.upload.name }}</td>
<td>{{ file.size }}</td>
<td>{{ file.file_type }}</td>
<td>{{ file.upload_datetime }}</td>
<td>
<form action="{{ download_file_url }}" method="post">
{% csrf_token %}
{{ form }}
<input type="hidden" name="path" value="{{ file.upload.name }}">
<input type="submit" class="btn btn-primary label-success" value="Download" />
</form>
</td>
</tr>
{% endfor %}
</tbody>
</table><hr>
views.py
def files_upload(request):
context = {}
if request.method == 'POST':
uploaded_file = request.FILES['my_file']
if uploaded_file.content_type not in file_content_types:
print("INVALID CONTENT TYPE")
else:
new_file = File(upload=uploaded_file, file_type=uploaded_file.content_type)
new_file.save()
print(uploaded_file.content_type)
qs = File.objects.all().order_by('-upload_datetime')
context['files'] = qs
context["file_types"] = file_content_types
file_type_counts = []
for file_type in file_content_types:
count = File.objects.filter(file_type=file_type).count()
file_type_counts.append(count)
context["file_type_counts"] = file_type_counts
return render(request, "files_ul_dl.html", context)
def download_view(request):
if request.method == 'POST':
path = request.POST.get('path')
print(path)
file_path = os.path.join(settings.MEDIA_ROOT, path)
if os.path.exists(file_path):
with open(file_path, 'rb') as fh:
response = HttpResponse(fh.read(), content_type="application/force-download")
response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path)
return response
raise Http404

How to generate PDF in Django Generic Views?

I have a template that is rendered by generic List View. I want to give a download link in front of each row of data in table. The download link will create a PDF file of respective rows data. Please tell me how to write a code for that?
Views.py
class BookingConfirmationListView(LoginRequiredMixin, generic.ListView):
model = container_booking
template_name = 'home/booking_confirmation_detail.html'
context_object_name = 'all_container'
def get_queryset(self):
return container_booking.objects.all()
Templates look like
<table class="table-striped table-hover table-bordered" width="100%">
<tr>
<th>Date</th>
<th>Source</th>
<th>Destination</th>
<th>Container</th>
<th>Commodity</th>
<th>Agreed Rate</th>
<th>Edit</th>
<th>Delete</th>
<th>Status</th>
</tr>
{% for item in all_container %}
<tr>
<td>{{ item.date }} </td>
<td>{{ item.place_of_reciept }} </td>
<td>{{ item.final_place_of_destination }} </td>
<td>{{ item.equipment_type }}{{ item.quantity }} </td>
<td>{{ item.commodity }} </td>
<td>{{ item.agreed_rate }} </td>
<td><a href="{% url 'home:cont_bk-update' item.id %}" ><i class="fas
fa-edit"></i></a></td>
<td><a href="{% url 'home:cont_bk-delete' item.id %}" ><i class="fas
fa-trash"></i></a></td>
<td>{{ item.approved }}</td>
</tr>
{% endfor %}
</table>
urls.py
url(r'^cont_bkdetail$', views.BookingConfirmationListView.as_view(),
name='cont_bk-detail'),
url(r'^cont_bk/(?P<pk>[0-9]+)/$',
views.BookingConfirmationUpdate.as_view(), name='cont_bk-update'),
url(r'^cont_bk/(?P<pk>[0-9]+)/delete/$',
views.BookingConfirmationDelete.as_view(), name='cont_bk-delete'),
I want that whenever I click download, the PDF file of that row is generated.

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!