Django Reduce the template Rendering Time - javascript

I am using Django 1.7 and nginx.
My sample view file is,
def testing(request):
return render_to_response('pages/testing.html', )
def testing1(request):
return render_to_response('pages/comingsoon.html',)
def testing2(request):
x= User.objects.all()
return render_to_response('pages/index1.html',{'users': x,})
def testing3(request):
context = User.objects.all()
return render_to_response('pages/testing.html',)
pages/testing.html - contains only text.(pure text)
pages/testing1.html - contains css and js
pages/testing2.html -
<body>
<h1>Users</h1>
{% for e in users %}
<table>
<tr>
<td class="active">{{ e.username }}</td>
<td>{{ e.email }}</td>
</tr>
</table>
{% endfor %}
</body>
pages/testing3.html - contains same as testing1.html
But while running this .
testing, testing1 take less than 3seconds in server.
But testing3 takes 40seconds and testing2 takes more that 1 Min.
How could I reduce that?
Thanks In Advance.

You may use values_list or values
and specify the values you need in templates inside values_list or values, instead of User.objects.all(). This is going to make a huge diffrence.

Related

How to avoid writing same code twice on a dynamic websocket site in django templates and javascript?

In a django project, templates are used on the backend which render html that is displayed on the page. But when dealing with Channels (websockets) which receive 'notifications' from the server, I find that I have to re-write code in javascript to render the same html elements.
As an example, I started out with a HTML table element that in a django template page:
{% for t in tickets %}
<tr class="ticket-row">
<td>{{ t.id }}</td>
<td>
<a href="/tickets/{{ t.id }}">
{{ t.subject }}
</a>
</td>
<td>
<a href="/users/{{ t.user.id }}">
{{ t.user.name}}
</a>
</td>
<td class="tooltipped" data-tooltip="{{ t.date_time_updated }}">
{{ t.date_time_updated|naturaltime }}
</td>
<td class="tooltipped" data-tooltip="{{ t.date_time_created }}">
{{ t.date_time_created|naturaltime }}
</td>
....
When channels receives a notification in javascript, I want to insert another row to the table without refresh, so I write JS code to do so like this:
function insertTicketRow(ticket) {
document.getElementById("results").innerHTML = "Server: " + data.subject;
var table = document.getElementById('ticket_table');
var row = table.insertRow(1);
// Insert new cells (<td> elements) at the 1st and 2nd position of the "new" <tr> element:
var cellId = row.insertCell(0);
var cellSubject = row.insertCell(1);
var cellFrom = row.insertCell(2);
cellId.innerHTML = data.id;
cellSubject.innerHTML = linkElement("/tickets/" + data.id, data.subject);
cellFrom.innerHTML = linkElement("/users/" + data.user, data.author_name);
cellLastUpdated.innerHTML = data.date_time_updated;
cellCreatedOn.innerHTML = data.date_time_created;
....
}
Obviously this is not maintainable and I suspect the worst approach possible. What if I have 30 columns and not just a few? What about the attributes? Adding all this via javascript is doing the same work twice, AND, I have to put in extra logic to make the rendered HTML in javascript look the same like django's.
The question is, is there some method I can use to not write the same thing twice, but still be able to work with websockets and add elements to the page dynamically?

Sending data from JS to Python successfully but Flask render_template doesn't execute

I am using a Jinja loop to display a table of results in an html page. When someone clicks the button in a table row, the code should send the first column value in that row to the server. The server should then use the value to populate values in another page. All works fine except the render_template function in app.py isn't executing.
What am I doing wrong?
My last print(request_details) shows the data needed correctly. However the render_template that follows just doesn't want to execute.
HTML and JS:
{% extends "layout.html" %}
{% block body %}
<table>
<tr>
<th>Request ID</th>
<th>Origin</th>
<th>Destination</th>
<th>Distance</th>
<th>Cargo</th>
<th></th>
</tr>
{% for r in supplier_results %}
<tr>
<td>{{ r[0] }}</td>
<td>{{ r[2] }}</td>
<td>{{ r[3] }}</td>
<td>{{ r[4] }}</td>
<td>{{ r[5] }}</td>
<td><button onclick="passRequest({{ r[0]|safe }})">Offer</button></td>
</tr>
{% endfor %}
</table>
<script>
function passRequest(arg) {
let details = arg
console.log(details)
const request = new XMLHttpRequest()
request.open('POST', '/viewrequest/' + details)
request.send();
};
</script>
{% endblock %}
Python:
#app.route("/viewrequest/<int:details>", methods=["GET", "POST"])
def viewrequest(details):
# Retrieve request information with the request_id (details)
retrieve_request = f"SELECT * FROM requests WHERE request_id='{details}';"
cur.execute(retrieve_request)
request_details = cur.fetchall()
# Call the newoffer page and pass the request details
if request_details == []:
print("No data found")
return
else:
print(request_details)
return render_template("supplier/newoffer.html", request = request_details)

Fill out form with the results returned from search form Symfony

I have created a search form in Symfony in order to find a serial number.
I have another form that once the data from the 1st form is return to fill out the 2nd form.
My Controller :
// ========================= Search =========================
$formSearch = $this->createForm(SearchInstallationType::class);
$getInstallationClientBySerialNumber = $savRepo->getInstallationClientBySerialNumber ($request->get('search_installation')['search_client_serial_number']);
$serialNumber = $request->get('search_installation')['search_client_serial_number'];
The Render part :
return $this->render('att/att_client.html.twig', [
'controller_name' => 'AttController',
'formSearch' => $formSearch->createView(),
'formClientInfo' => $formClientInfo->createView(),
'dataSerialNumber' => $serialNumber,
'getInstallationClientBySerialNumber ' => $getInstallationClientBySerialNumber
]);
My TWIG Page :
{% for installClientInfo in getInstallationClientBySerialNumber %}
<tr id="installClientInfo_{{ installClientInfo.idRma }}">
<td onclick="test('{{ dataSerialNumber }}');">{{ installClientInfo.serialNumber }}</td>
{% for d in dataClientInfo %}
<td>{{d.modele}} <br/>
{{ d.marque }} <br/>
{{ d.codeArticle }}
</td>
{% endfor %}
My JS :
function test(dataSerialNumber){
console.log(dataSerialNumber)
}
The serial number is returned fine in the console log but all the other parameters I add end up undefined.
If anyone could help, you would be a life saver.
Thank you in advance.

How to select document Ids that are being populated via Flask on page load

I am using a submit button to pass form values into flask, which then populate the ids and values of an html table on another page.
I then want to select those values by their ids and use them to filter a dataset. However, I'm finding that when I try to use d3.select(#thing-id).value, I am getting back undefined, I think because the file which is selecting the ids is running before they are populated in the html.
I've tried to use a variety of selection methods including d3 and get Document by Id.
The Flask:
#app.route("/prediction", methods=["GET", "POST"])
def predict():
if request.method == 'POST':
new_film = [request.form["adults"], request.form["years"],
request.form["film_length"], \
request.form["genre_1"], request.form["genre_2"], request.form["genre_3"]]
def commentary(rating):
if rating <= 3:
comment = "This sucks worse than what Rachel said"
elif rating <= 6:
comment = "Mediocre at best"
else:
comment = "The best thing since sliced bread"
return comment
prediction = {
"adults_entered1": new_film[0],
"years_entered1": new_film[1],
"film_length_entered1": new_film[2],
"genre1_entered1" : new_film[3],
"genre2_entered1" : new_film[4],
"genre3_entered1" : new_film[5],
"prediction": commentary(rating[0]),
"rating": rating[0]
}
for key, value in prediction.items():
print(f"{key}: {value}")
return render_template('prediction.html', result=prediction)
The html:
<tbody id="filter-table"></tbody>
<tr>
{% if result %}
{% for key, value in result.items() %}
<td id={{key}}>
{{value}}
</td>
{% endfor %}
{% endif %}
</tr>
The Javascript:
filter_val = d3.select(#adults_entered1).value
console.log(filter_val)
I would expect to be returned the {{value}} for the adults_entered1. Instead it is undefined.

How to pass php parameters inside blade file using AngularJS?

I will try to be as clear as possible. I have a table with ng-repeat in blade file.
I want to send parameters to a Laravel function, inside the repeat loop.
Here is the example:
The angular
app = angular.module("myApp",[], function($interpolateProvider) {
$interpolateProvider.startSymbol('<%');
$interpolateProvider.endSymbol('%>');
});
The blade file : $idVal needs to be the id from the loop.
<tr ng-repeat="rec in recomends" ng-init="recomends = {{ $recomends }}">
<td ><% $index + 1 %></td>
<td><% rec.name %></td>
<td>{{ HelperAdmin::getTotalParam('quality',$idVal) }}</td>
</tr>
The laravel Function:
public static function getTotalParam($field,$reco_id){
$total = DB::select("SELECT AVG($field) AS mysum FROM recommendation_measure WHERE reco_id = $reco_id ");
return number_format($total[0] ->mysum,2);
}
I need to push $idVal as the id of the loop data. But I can't find a way to send it. Any idea?
Hope this question is clear.

Categories

Resources