Django admin table functionality in templates - django

Django has a nice sortable table system in the admin. I would like to know how can I use that in my regular templates.
I couldnĀ“t find any info about this. Any clues welcome.
Thanks in advance.

<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js "> </script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script>
$(document).ready(function() {
$('#example').DataTable();
} );
</script>
</head>
<body>
<table id="example" class="display" >
<thead>
<tr>
<th>name</th>
<th>position</th>
<th>office</th>
<th>age</th>
<th> date </th>
</tr>
</thead>
<tbody>
{% for i in qs %}
<tr>
<td>{{ i.name }}</td>
<td>{{ i.position }}</td>
<td>{{ i.office }}</td>
<td>{{ i.age }}</td>
<td> {{ i.date }} </td>
</tr>
{% endfor %}
</tbody>
</table>
</body>
</html>

Related

how can i stop to run path with same parameter on continue path

here i send my details
how can i stop this for example if i run http://127.0.0.1:7000/search_acctable/?txt=Kalpesh but if now i again run my code this is run like http://127.0.0.1:7000/search_acctable/?txt=Kalpesh/search_acctable/?txt=any in django how can i solve this
i need help to solve this problem
views.py
def s_index(request):
current_url = request.build_absolute_uri()
#print(current_url)
src = request.POST.get('txt_search')
#if request.POST['btn_clear']:
# return HttpResponseRedirect(request.META.get('HTTP_REFERER')) # return to previous page
if request.POST['btn_search']:
rec=accmaster.objects.filter(Q(acc_name__contains=src) | Q(acc_city__contains=src)| Q(acc_op__contains=src) ).values() # for filter with and conition onyl put comma if want or condition use pipe sign and Q
if rec.exists():
rec=accmaster.objects.filter(Q(acc_name__contains=src)| Q(acc_city__contains=src)| Q(acc_op__contains=src)).values()
grp_city=accmaster.objects.filter( Q(acc_name__contains=src) | Q(acc_city__contains=src)| Q(acc_op__contains=src)).values('acc_city').annotate(Sum('acc_op')).order_by('acc_city')
template=loader.get_template('index.html')
output=accmaster.objects.filter(Q(acc_name__contains=src)| Q(acc_city__contains=src)| Q(acc_op__contains=src)).values().aggregate(Sum('acc_op'))
context ={
'rec':rec,
'output':output['acc_op__sum'],
'grp_city':grp_city,
}
return HttpResponse(template.render(context,request))
else :
return HttpResponseRedirect(request.META.get('HTTP_REFERER')) # return to previous page
urls.py
from django.urls import path
from . import views
urlpatterns=[
path('',views.index,name='index'),
path('addacc/',views.add,name='addacc'),
path('addacc/addrecord/',views.addrecord,name='addrecord') ,
path('delete/<int:id>',views.delete,name='delete') ,
path('update/<int:id>',views.update,name='update'),
path('update/updaterecord/<int:id>',views.updaterecord,name='updaterecord'),
path('index/',views.s_index,name='s_index'),
#path('',views.form_view,name='mform')
]
index.html
{% load static %}
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function printreport(){
//var divtoprint=document.getElementById("maindiv");
var printcontext=document.getElementById("maindiv").innerHTML;
var originalcontext=document.body.innerHTML;
var nwin=window.open("");
nwin.document.open();
nwin.document.write('<html><head><link rel="stylesheet" media="print" href="{% static 'mystyleprint.css' %}" ></head><body>');
nwin.document.write(printcontext);
nwin.document.write("</body></html>");
//document.write(printcontext);
//document.body.innerHTML=printcontext;
//printWindow.document.write(divtoprint);
nwin.print();
nwin.document.close();
nwin.close();
}
</script>
<link rel="stylesheet" href="{% static 'mystyle.css' %}" >
<link rel="stylesheet" href="{% static 'mystyleprint.css' %}" media="print"> <!-- make seprate css for print document and make media print-->
</head>
<body >
<form action="index/" method="post" >
{% csrf_token %}
<div>
<button type="button">Add Account</button>
<label>Search :</label> <input id="txt_search" name="txt_search" autocomplete="off">
<input type="submit" id="btn_search" name="btn_search" value="Search" onclick="myfunction()">
<input type="button" id="btn_clear" name="btn_clear" value="clear"" onclick="history.back()">
<input type="button" name="btn_print" value="Print" onclick="printreport()">
</div>
<br>
<div id="maindiv">
<table id="maintable">
{% with no="s" %}
<h1> Account List </h1>
<tr>
<th> Sr.No </th>
<th> Name </th>
<th> City </th>
<th> Opening Balance </th>
<th id="thedit"> Edit </th>
<th id="thdelete"> Delete </th>
</tr>
{% for y in grp_city %}
<tr>
<td id="tdcity" colspan=4 style="color:magenta"> {{ y.acc_city }}</td>
{% for x in rec %}
{% if x.acc_city == y.acc_city %}
<tr>
<td style="width:4%" id="srno"></td>
<td>{{ x.acc_name }}</td>
<td style="width:20%"> {{ x.acc_city}}</td>
<td align="right" style="width:10%"> {{ x.acc_op}}</td>
<td style="width:4%" id="redit"> <img src="{% static 'icon/update.png' %}"></td>
<td style="width:4%" id="rdelete"> </td>
</tr>
{% endif %}
{% endfor %}
<td colspan=4 align="right" style="color:magenta; font-size:18px;" >Total: {{ y.acc_op__sum|floatformat:2 }} </td>
<td colspan=2 id="nodisp"> </td>
</tr>
{% endfor %}
<tr>
<td colspan=4 align="right" style="color:red; font-size:20px">Total : {{output|floatformat:2}} </td>
</tr>
</table>
</div>
<p>
</p>
{% endwith %}
</form>
</body>
</html>
i don't know to how to handle it i am new to django

Why django template not render tag after include tag

i consider that why template not render tag after {% include %}. when i put some tag like something in front of include tag, it work. But it not work if i try to put behind the include tag. :(
in index.html
<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>Document</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.0/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous">
<link rel="stylesheet" href="{% static 'styles/main.css' %}" />
<script
src="https://cdn.jsdelivr.net/npm/bootstrap#5.2.0/dist/js/bootstrap.bundle.min.js"
integrity="sha384-A3rJD856KowSb7dwlZdYEkO39Gagi7vIsF0jrRAoQmDKKtQBHUuLZ9AsSv4jD4Xa" crossorigin="anonymous">
</script>
</head>
<body>
<div class="d-flex">
{% include 'navbar.html' %}
<div class="content">
<div class="header">
{% include 'header.html' %}
</div>
<div>
{% block subHeader %}
{% endblock %}
</div>
<div>
{% block list %}
{% endblock %}
</div>
</div>
</div>
</body>
</html>
in list.html
<table class="table">
<thead>
<tr>
<th scope="col">Cardinal Number</th>
<th scope="col">ID</th>
<th scope="col">Name</th>
<th scope="col">Category</th>
<th scope="col">Cost</th>
<th scope="col">Note</th>
<th scope="col">Image</th>
<th scope="col">Action</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">1</th>
<td>Mark</td>
<td>Otto</td>
<td>#mdo</td>
</tr>
<tr>
<th scope="row">2</th>
<td>Jacob</td>
<td>Thornton</td>
<td>#fat</td>
</tr>
<tr>
<th scope="row">3</th>
<td colspan="2">Larry the Bird</td>
<td>#twitter</td>
</tr>
</tbody>
</table>
in products.html
{% extends 'index.html' %}
{% block subHeader %}
{% include 'components/subHeader.html' with url="api/add-product" name="product"
selectName="product-category" %}
{% endblock subHeader%}
{% block list %}
{% include 'components/list.html' %}
{% endblock content%}
although i put whatever after include tag in block subHeader, it not work. i dont understand why that. Can someone point me ? Thanks

Django - AttributeError at / 'tuple' object has no attribute 'get'

I am getting an attribute error at:
Exception Location: C:\Users\user\Desktop\django-basics\env\lib\site-packages\django\middleware\clickjacking.py, line 26, in process_response
This is the said location (the process_response function):
def process_response(self, request, response):
# Don't set it if it's already in the response
if response.get('X-Frame-Options') is not None:
return response
My views file
from django.shortcuts import render
from .models import Student
def studentlist(request):
get_students = Student.objects.all()
data = {
'get_students' : get_students
}
return render(request, 'studentlist.html', data)
My templates file studentlist.html:
{% load static %}
<link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}" />
<title>Student List</title>
</head>
<body>
<div class="container">
<h2 class="text-center mt-5">Student List</h2>
<table class="table table-hover table-dark">
<thead>
<tr>
<th scope="col">Roll No.</th>
<th scope="col">Photo</th>
<th scope="col">Full Name</th>
<th scope="col">Gender</th>
<th scope="col">Course</th>
<th scope="col">Grade in course</th>
</tr>
</thead>
<tbody>
{% for student in get_students %}
<tr>
<td>{{ student.roll_no }}</td>
<td>
<img src="{{ student.photo.url }}" width="40" height="40"/>
</td>
<td>{{ student.full_name }}</td>
<td>{{ student.course }}</td>
<td>{{ student.grade }}</td>
<td>{{ student.gender }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
Please let me know if I need to add more info. Thanks in advance.
if someone has the same issue, the answer from Willem van Onsem was the one that fixed my issue, I had a coma at the end.

CSV File into Django Template

I have an app that uploaded a file using the FileField(). Uploading the file works excellently but I have a problem on how to display the CSV file content into an HTML table where headings goes to the table header while the rows/lines of the CSV file goes to the appropriate cell in an HTML table.
For now i have a little success in retrieving the CSV file's columns. Here are the snippets.
Method:
# retrieve datafarame's columns
def get_columns(file):
df = pd.read_csv(file)
cols = df.columns
return cols
HTML:
<table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">
<thead>
<tr>
{% for col in columns %}
<th>{{ col }}</th>
{% endfor %}
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
If you are using pandas in the backend, then you can pass the dataframe.to_dict() from the view which will give you a list of dictionaries. You can iterate over the list of rows in your template.
views.py
def myview(request):
df = pd.read_csv(file)
return render(request, 'my_view.html', {'columns': df.columns, 'rows': df.to_dict('records')})
template.html
<table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">
<thead>
<tr>
{% for col in columns %}
<th>{{ col }}</th>
{% endfor %}
</tr>
</thead>
<tbody>
{% for index, row in rows %}
<tr>
<td>{{row.name}}</td>
<td>{{row.email</td>
</tr>
{% endfor %}
</tbody>
</table>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Detect Outliers</title>
</head>
<body>
<button type="button">Upload</button>
<h1>Uploaded Data</h1>
<table border="1px">
<tr>
{% for data in DataFrame %}
<th>{{ data }}</th>
{% endfor %}
{% for _, record in DataFrame.iterrows %}
<tr>
{% for value in data %}
<td>{{ value }}</td>
{% endfor %}
</tr>
{% endfor %}
</tr>
</table>
</body>
</html>

Datatables with Django

Has anyone tried to use DataTables with Django? I could not seem to get it to work, I had everything in the static files, etc..
Once I try and use datatables, I lose all the template styling and it just goes back to a default table.
EDIT There is not error when I load the page, all the data shows up just no template or datatables effects loading
This is the code:
{% load static %}
{% block content %}
<script src="{% static "assets/js/jquery.datatables.js" %}" type="text/javascript"> </script>
<script src="{% static "assets/js/jquery.js" %}" type="text/javascript"></script>
<link rel="stylesheet" href="{% static "assets/css/jquery.dataTables.css" %}" type="text/css"/>
<h1>Full list of supported Golf Courses:</h1>
<br>
<script type="text/javascript" charset="utf-8">
$(document).ready( function () {
$('#courses').dataTable();
} );
</script>
<table id="courses" class="display">
<tr>
<th>Golf Course</th>
<th>Front 9</th>
<th>Back 9</th>
<th>Total Par</th>
</tr>
{% for course_name, par_front_9, par_back_9, total_par in data %}
<tr>
<td>{{ course_name }}</td>
<td>{{ par_front_9 }}</td>
<td>{{ par_back_9 }}</td>
<td>{{ total_par }}</td>
</tr>
{% endfor %}
</table>
</div>
{% endblock %}
Got it working, noticed that the code worked when removing {% extend "base.html" %}. Fixed it by using {% include "base.html" %}