Flask Button click not generating POST message - ajax

I am using flask to generate a single webpage.
The webpage has couple of text boxes and a button.On button click, I am planning to display table in the same page with the values fetched from the inputs.
Below is the flask code in python
===========================
#app.route('/')
def index():
return render_template('index.html')
#app.route('/ApplyFilter',methods=['POST','GET'])
def ApplyFilter():
print("Hello")
if request.method == 'POST':
import CompareDataset as cmp
df3= cmp.CompareDataset()
#conver the dataframe to the json objects
AllRecords = json.loads(df3['both'].to_json(orient="records"))
# count the number of records
totalItems = df3['both']["Client"].count()
client=request.form["client"]
account= request.form["account"]
auditstatus = request.form["auditstatus"]
effectivedate=request.form["effectivedate"]
cyclecode=request.form["cyclecode"]
return
jsonify({'data':render_template('ApplyFilter.html',AllRecords=AllRecords,totalItems=totalItems)})
return redirect('/')
snapshot of the html is as below
<td>
Apply Filter</button>
</td>
</tr>
</table>
</div>
</div>
{% if AllRecords %}
<div class="container-fluid bg-3 text-left">
<div class="counter"><span>Total Records Found : {{ totalItems }}</span></div>
<div "border-bottom: 1px solid #ddd; overflow-y: scroll;" >
<table class="table" style="width: 90%; height: 100%;" >
<thead style="color: #333; background-color: #f1f1f1">
<tr>
<th>Audit Status</th>
<th>Client</th>
<th>Effective Date</th>
<th>Source System Code</th>
<th>Account Number</th>
<th>Cycle Code</th>
<th>AuditTrailtimeStamp</th>
</tr>
</thead>
<tbody>
<tr class="success" >
{% for key,value in AllRecords.iterrows() %}
<td>{{ value["AuditStatusCode"] }}</td>
<td>{{ value["Client"] }}</td>
<td>{{ value["EffectiveDate"] }}</td>
<td>{{ value["SourceSystemCode"] }}</td>
<td>{{ value["InternalAccountId"] }}</td>
<td>{{ value["CycleCode"] }} </td>
<td>{{ value["AuditTrailtimeStamp_x"] }} </td>
{% endfor %}
</tr>
</tbody>
</table>
</div>
</div>
{% endif %}
</form>
The java script tagged to button is as below
$(function() {
$('a#applyfilter').bind('click', function() {
$.getJSON('/ApplyFilter', {
client : $("client").val(),
account : $("account").val(),
auditstatus : $("auditstatus").val(),
auditstatus : $("auditstatus").val(),
effectivedate :$("effectivedate").val(),
cyclecode : $("cyclecode").val(),
}, function(data) {
data = data.data;
});
return false;
});
});
On button click ApplyFilter is getting called. But it is not generating the POST message
127.0.0.1 - - [07/Jul/2018 17:45:40] "GET / HTTP/1.1" 200 - Hello
127.0.0.1 - - [07/Jul/2018 17:45:43] "GET /ApplyFilter HTTP/1.1" 302 -
127.0.0.1 - - [07/Jul/2018 17:45:43] "GET / HTTP/1.1" 200 - Hello
The applyfilter button is not generating the post call and hence in the route Applyfilter , the if condition is not satsifying.
Please assist and advise as to what I am missing.

There are many problems with this code and I'm still a bit confused by what you're trying to accomplish but I'll answer your question for now.
Your logs tell you exactly what the problem is. You want that if statement to run when you send a post request. But your logs show that you are receiving a get request and returning a 302 which indicates you have been redirected which is what is happening at the bottom of your method. So if you're sending a get request, an if statement that checks if you're using a post request isn't going to fire.
127.0.0.1 - - [07/Jul/2018 17:45:43] "GET /ApplyFilter HTTP/1.1" 302 -
You seem to be using getJson() when you should be using something like the post() method.
But there are other problems such as this section won't do anything
jsonify({'data':render_template('ApplyFilter.html',AllRecords=AllRecords,totalItems=totalItems)})
return redirect('/')
For some reason you're jsonifying a call to render_template and then doing nothing with it? I can't even think what you're trying to achieve by jsonifying render_template when that function will only work within your Flask app. I may just be misunderstanding you so apologies if I am, feel free to clarify further and I'll do my best to help.

Related

How to auto refresh html table fields rendered with a for loop in flask?

Snippet from the function in Flask.
I'm generating a list of all positions and then sending them over. Then using jinja and the for loop I'm populating the table.
#app.route("/")
def table_list():
position_list=["a","b","c","d"]
return render_template("index.html",
position=position_list)
This is on the homepage and needs to be automatically refreshed every couple of seconds so the position values will get updated.
The HTML table:
<table>
<tbody id="data">
{% for pos1, pos2, pos3, pos4 in position %}
<tr id="data_table">
<td id="pos1"> {{ pos1 }} </td>
<td id="pos2"> {{ pos2 }} </td>
<td id="pos3"> {{ pos3 }} </td>
<td id="pos4"> {{ pos4 }} </td>
{% endfor %}
</tbody>
</table>
How do I use JS to refresh only the values in the table, and automatically every couple of seconds?
You will have to change multiple things to make this work.
Separate endpoint into html endpoint and web-service endpoint.
#app.route("/table_list")
def table_list():
return render_template("index.html")
#app.route("/get_list")
def get_list():
position_list = ["a", "b", "c", "d"]
return make_response({"output": position_list})
Change the html for table
<table>
<tbody id="data">
<tr id="data_table">
</tr>
</tbody>
</table>
Change the html template to keep calling get_list and refresh the html
</body>
<script>
setInterval(function () {
let myRequest = new Request('/get_list');
fetch(myRequest).then(response => response.json()).then(function (data) {
let data_table = document.getElementById("data_table");
data_table.innerHTML = "";
for (let d in data['output']) {
data_table.innerHTML += `<td>${data['output'][d]}</td>`
}
});
}, 1000);
</script>
</html>

Retrieve image from django

I am completely beginner in Django, trying to make a table, which gets data from the Django database(included image). Here before adding the image field in the Django model, all was working perfectly. but I cannot get an image from the Django media file(I also upload images with superuser and Django form both, and they worked perfectly). here is my approach below-
in views.py:
def index(request):
table_data = TableA.objects.order_by('roll')
index_dict = {'insert_me' : "hello this is from views.py",
'dynamic_table' : table_data,
}
return render(request, 'app26/index.html', context=index_dict)
in HTML:
{% if dynamic_table %}
<table class="table table-striped">
<thead class="thead-dark">
<tr>
<th>Name</th>
<th>Roll</th>
<th>Email</th>
<th>Password</th>
<th>Address</th>
<th>Profile Pic</th>
</tr>
</thead>
<tbody>
{% for i in dynamic_table %}
<tr>
<td>{{ i.name }}</td>
<td>{{ i.roll }}</td>
<td>{{ i.email }}</td>
<td>{{ i.password }}</td>
<td>{{ i.address }}</td>
<td><img class="profile-pic" src="{{media_url}}{{ i.profile_pic }}" alt=""></td>
</tr>
{% endfor %}
</tbody>
</table>
{% else %}
<p>sorry cannot load the data for technical error</p>
{% endif %}
in urls.py
from django.conf import settings
from django.conf.urls.static import static
urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
I've also set up MEDIA_URL and MEDIA_ROOT. From the Admin I can upload images and they are ok.
in settings.py:
MEDIA_ROOT = os.path.join(BASE_DIR, 'Media')
MEDIA_URL = '/images/'
Now my problem is nothings is show in the profile pic column in the table, even any error is not showing.
Please suggest me how can I get the image file from the database for my this uses
I think the main reason the images where not being displayed was because the path to your media_url was not added into the render function. See below:
def index(request):
img = Upload.objects.filter(file_type='image')
index_dict = {
'insert_me' : "hello this is from views.py",
'dynamic_table' : table_data,
'media_url': settings.MEDIA_URL
}
return render(request, 'app26/index.html', context=index_dict)
Give it a shot!

Angular 8 Pagination with Data from Database --

I am having a little trouble with this one.
Using the approach discussed in this -- https://jasonwatmore.com/post/2019/06/18/angular-8-simple-pagination-example
Use-case difference is, my data all comes from database. So I have had to use a model class and all. But, due to some problem, I am getting the same data [1st row from db] in all the rows. Let me post the code I used --
ANGULAR
method inside my component to get data from service class
newsTopics: NewsTopic[];
pageOfItems: Array<NewsTopic>;
getAllNewsTopics() {
this.userService.getAllTopics()
.subscribe((data: NewsTopic[]) => {
this.newsTopics = (data as NewsTopic[]).map((x, i) => ({ Id: (i + 1), TopicId: data[0].TopicId, TopicName: data[0].TopicName, TopicInfo: data[0].TopicInfo, IssueStartDate: data[0].IssueStartDate, IssueCloseDate: data[0].IssueCloseDate, NewsCategory_Id: 0 }));
})
}
my model class
export class NewsTopic
{
Id: number;
TopicId: string;
TopicName: string;
TopicInfo: string;
IssueStartDate: Date;
IssueCloseDate: Date;
NewsCategory_Id: number;
}
the method in service class itself
getAllTopics(){
var reqHeader = new HttpHeaders({ 'No-Auth': 'True' });
return this.http.get<NewsTopic[]>(this.rootUrl + '/api/NewsTopic/GetAllNewsTopics', { headers: reqHeader });
}
my html for showing the data and the pagination control
<div class="card-body">
<table class="table table-striped" id="newstopics_tbl">
<thead>
<tr style="background:linear-gradient(50deg, #d9fcfc, #dafbde)">
<th>Topic ID</th>
<th>Topic Name</th>
<th>Topic Info</th>
<th>Start Date</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let nt of pageOfItems">
<td><b>{{nt.TopicId}}</b></td>
<td>{{nt.TopicName}}</td>
<td>{{nt.TopicInfo}}</td>
<td>{{nt.IssueStartDate}}</td>
</tr>
</tbody>
</table>
</div>
<div class="card-footer pb-0 pt-3" style="background:linear-gradient(50deg, #d9fcfc, #dafbde); margin-top:15px">
<jw-pagination [items]="newsTopics" (changePage)="onChangePage($event)"></jw-pagination>
</div>
My guess is, the problem lies in the getAllNewsTopics() method, where I am trying to fill and map the array of objects and assign to the variable. Something wrong there. If you see the original example from the link, they used a .fill(0) also. In my case I tried doing .fill(data[0]) however result is the same, ie. only first record, repeated multiple times.
What is the trick I am missing? Can someone just point me out.
Much needed, Thanks,
EDITS --
These are the changes->
getAllNewsTopics() {
var reqHeader = new HttpHeaders({ 'No-Auth': 'True' });
return this.http.get<NewsTopic[]>(this.rootUrl + '/api/NewsTopic/GetAllNewsTopics', { headers: reqHeader })
.subscribe((data: NewsTopic[]) => {
this.newsTopics = data;
});
}
and
<div class="card-body">
<table class="table table-striped" id="newstopics_tbl">
<thead>
<tr style="background:linear-gradient(50deg, #d9fcfc, #dafbde)">
<th>Topic ID</th>
<th>Topic Name</th>
<th>Topic Info</th>
<th>Start Date</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let nt of pageOfItems" style="cursor:pointer" (click)="NewsArticleAdd(nt)">
<td (click)=""><b>{{nt.TopicId}}</b></td>
<td style="color:mediumvioletred;" (click)="">{{nt.TopicName}}</td>
<td (click)="">{{nt.TopicInfo}}</td>
<td (click)="">{{nt.IssueStartDate}}</td>
</tr>
</tbody>
</table>
</div>
<div class="card-footer pb-0 pt-3" style="background:linear-gradient(50deg, #d9fcfc, #dafbde); margin-top:15px">
<jw-pagination [items]="newsTopics" (changePage)="onChangePage($event)"></jw-pagination>
</div>
That does the trick. Works as expected,

Laravel Blade change row color when variable value is different in loop

I have a report page that loops through a collection and displays the data in a generic bootstrap template table - it's showing data about users, and one user can have multiple rows in the table. I group the rows by the user ID and I want to basically stripe the table rows based on the user ID (not just alternating rows). So, for example, I might display 4 rows for user ID = 5 with a white background and then 2 rows for user ID = 6 with a gray background. I'd just use a local variable in straight php, but is there an elegant/clean way to do this in the blade templates?
#foreach($payments->getDetails() AS $k=>$detail)
<tr>
<td>{{ $detail->payment->userid }}</td>
<td>${{ $detail->payment->amount }}</td>
<td>{{ $detail->payment->status }}</td>
</tr>
#endforeach
In this example, $payments is a collection of $paymentsDetails objects. So based on the $detail->payment->userid value I'd like to determine the class or background color.
Thank you for any help in this.
Just a thought... This assumes the rows are ordered by user id naturally (it would not work otherwise in your example anyway...)... So here's the thought...
If the user id is odd, then give it a color, if it is even, give it the alternate color... that would work... Sort of ...
#foreach($payments->getDetails() AS $k=>$detail)
<tr>
<td class="{{$detail->payment->userid % 2 == 0 ? 'evenColor':'oddColor'">{{ $detail->payment->userid }}</td>
<td class="{{$detail->payment->userid % 2 == 0 ? 'evenColor':'oddColor'">{{ $detail->payment->amount }}</td>
<td class="{{$detail->payment->userid % 2 == 0 ? 'evenColor':'oddColor'">{{ $detail->payment->status }}</td>
</tr>
#endforeach
Something like this would also work... not sure I like it though
#foreach($payments->getDetails() AS $k=>$detail)
#if($detail->payment->userid % 2 == 0)
<tr>
<td class="evencolor">{{ $detail->payment->userid }}</td>
<td class="evencolor">>${{ $detail->payment->amount }}</td>
<td class="evencolor">{{ $detail->payment->status }}</td>
</tr>
#else
<tr>
<td class="oddcolor">{{ $detail->payment->userid }}</td>
<td class="oddcolor">${{ $detail->payment->amount }}</td>
<td class="oddcolor">{{ $detail->payment->status }}</td>
</tr>
#endif
#endforeach
Anyway... just a possible direction... someone else might have a more elegant idea...
I got the solution to this via www.laracasts.com from user #Cronix:
I'd do it the way you were thinking originally and just use
#php/#endphp blade directives to determine if the userid has changed
during each loop iteration and if it does change the color.
#php
$lastid = null;
$rowclass = 'grey';
#endphp
#foreach($payments->getDetails() AS $k=>$detail)
#php
//if userid changed from last iteration, store new userid and change color
if ($lastid !== $detail->payment->userid)
{
$lastid = $detail->payment->userid;
if ($rowclass == 'grey') $rowclass = 'white';
else $rowclass = 'grey';
}
#endphp
<tr class="{{ $rowclass }}">
<td>{{ $detail->payment->userid }}</td>
<td>${{ $detail->payment->amount }}</td>
<td>{{ $detail->payment->status }}</td>
</tr>
#endforeach
If anyone out there has a more elegant Blade-focused idea on how to solve it, I'd love to hear about it.
hey guys the methods above failed for me, incase anyone els needs this : im using laravel 5.4 with php 5.6===> this is what has worked for me;
#php
if ( $post->dbdata == 'approved'):
$color = 'green';
elseif ( $post->dbdata == 'Pending'):
$color = 'yellow';
elseif ( $post->dbdata == 'rejected'):
$color = 'red';
else:
$color = 'black';
endif;
#endphp
<tr style="background-color: {{$color}}">
<td>
<h6>{{ $post->dbdata }}</h6>
</td>
</tr>

ng-repeat causing "Error: 10 $digest() iterations reached. Aborting! when passing scope to leaflet directive

Edited: After some advices i came back to old version of how i wanted handle angular and leaflet, link to fiddler but still is not working,
Explanation: It was working with angular-leaflet-directive, but this directive has very bad performance on firefox, to compare leaflet.js self is very good so i thought i will try to make some small directive on my own, maybe somebody has some advices what is wrong and how to fix it?
Link to fiddler:
fiddler
I try to pass result from ng-repeat to leaflet directive, but when i do it, angular start "Error: 10 $digest() iterations reached. Aborting!, there is no problem when i pass just data to directive. I tried few things but without result. I cannot even see markers. If the problem is in directive?
<body ng-app="directoryAppMap">
<div ng-controller="DirectoryMapListController">
<input ng-model="search" placeholder="Name" />
<table id="table">
<thead>
<tr>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="hf in FilteredGeojson = (data | filter:search)">
<td>{{ hf.properties.name }}</td>
<td>{{ hf.geometry.coordinates }}</td>
</tr>
</tbody>
</table>
<div leaflet-directive id="map" data="FilteredGeojson"></div>

Resources