Using flask, I want to select a user from a table and then redirect the page with the id of the selected user. My code looks something like this:
HTML:
<form action="" method="POST">
<table>
<tr>
<th>Id</th>
<th>First Name</th>
<th>Last Name</th>
</tr>
{% for user in users %}
<tr type="submit" name="action" value="{{user.user_id}}">
<td>{{user.user_id}}</td>
<td>{{user.first_name}}</td>
<td>{{user.last_name}}</td>
</tr>
{% endfor %}
</table>
</form>
Python:
def userSelect():
if request.method == 'POST':
return redirect(url_for('user', user=request.form['action']))
return render_template('userSelect.html', users=user.query.all())
I have also tried using JQuery to make the post, but I am unsure how to then use the id in the page that I redirected to, and I can't redirect from flask after having made a post from JQuery:
$("table tr").on("click",function()
{
var selected = $("td:first", this).text();
$.post("/user", {user_id: selected}, function(){
window.location.href = "/user";
});
});
EDIT:
Let's just say I want to display that id on the page I redirect to (something like this):
#app.route("/user")
def user(user):
return user
With your Jquery's code, it will make an ajax to server
$.post("/user", {user_id: selected}, function(){
window.location.href = "/user";
});
so, Flask can not redirect, if you edit code look like:
$.post("/user", {user_id: selected}, function(data){
console.log(data);
});
you will see Flask had returned HTML of the redirected page.
Finally, I think this is help you:
Flask:
#app.route('/user/<user_id>')
def userHasSelected(user_id):
....
// I don't know why do you need this return redirect
return redirect(url_for('user', user=request.form['action']))
JS:
$("table tr").on("click",function()
{
var selected = $("td:first", this).text();
// {{url_for('user', user_id=selected)}} it will be rending from server
window.location.href = {{url_for('user', user_id=selected)}}
// or
window.location.href = `/user?user_id=${selected}`;
});
Related
There is a list generated in HTML, that represents all objects (Cards).
There is already a delete button, but it's using Django functionality, and it requires a page to reload to take effect.
Is there a simple way to include AJAX into the program?
I am a beginner to JavaScript and AJAX. I have tried some copy-paste solutions. I even tried to deconstruct a simple Django Ajax CRUD app, but it has too many functionalities, and it seemed like an overkill for my app (i would have to rewrite all the views, templates and urls).
So I decided to ask a question over here with my own code.
views.py (List objects view)
def all_cards(request):
cards = Card.objects.all()
return render(request, 'all_cards.html', {'cards':cards})
all_cards.html
<body>
{% if cards %}
<table class="table" id="card-table">
<tr>
<th>Card owner name</th>
<th>Card balance</th>
</tr>
{% for card in cards %}
<tr>
<td>{{ card.cardholders_name }}</td>
<td>{{ card.card_balance }}€</td>
<td><form action="{% url 'card_delete' card.id %}" method="post">
{% csrf_token %}
<input type="submit" value='Delete'>
</form></td>
</tr>
{% endfor %}
{% else %}
<p>There are no cards registered.</p>
{% endif %}
</table>
</body>
urls.py
url(r'(?P<id>\d+)/$', views.card_delete, name='card_delete'),
views.py (Delete object view)
def card_delete(request, id):
card_that_is_ready_to_be_deleted = get_object_or_404(Card, id=id)
if request.method == 'POST':
card_that_is_ready_to_be_deleted.delete()
return HttpResponseRedirect('/all_cards')
As you can see, the form's input(
<input type="submit" value='Delete'>
)calls Django's view via URL.
I expect the delete button to call an AJAX functionality, that will do a similar thing.
How should I go about writing that functionality?
P.S.: This is my first StackOVerflow question, I'm open for constructive criticism.
You should add id to your form and table row first
<form action="{% url 'card_delete' card.id %}" method="post" id="delete_form_{{ card.id }}">
.
<tr id="card_{{card.id}}">
And change button code to:
<input type="button" onclick="submit_delete({{ card.id }})" value="delete">
And use this function to send AJAX request:
<script>
function submit_delete(id) {
$.ajax({
type: $('#delete_form_'+id).attr('method'),
url: $('#delete_form_'+id).attr('action'),
data: $('#delete_form_'+id).serialize(),
success: function (data) {
$('#card'+id).remove()
}
});
}
</script>
I am new to AngularJS and Djnago Rest Framework. I have created one web api which return list of customers in JSON format. I am getting proper data in RESTClient add-on of mozilla firefox. But i am not able to get data in AngularJS script.
Here i have attached all the codes and error image as below:
views.py (API code)
class CustomerListView(APIView):
renderer_classes = (JSONRenderer, )
def post(self, request, format=None):
content = []
customer_list = Customer_tbl.objects.all()
if customer_list:
for customer in customer_list:
content.append({
'first_name': customer.cus_first_name,
'last_name': customer.cus_last_name,
'email': customer.cus_email,
'contact': customer.cus_contact
})
return Response(content)
test.html
<!DOCTYPE html>
<html ng-app="myTestModule">
<head>
<script src="../scripts/angular.js"></script>
<script src="../scripts/sample_page_test.js"></script>
<link href="../css/style_new.css" rel="stylesheet" />-->
</head>
<body>
<div ng-controller="customerController">
<table>
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Contact</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="customer in customers">
<td>{{ customer.first_name }}</td>
<td>{{ customer.last_name }}</td>
<td>{{ customer.email }}</td>
<td>{{ customer.contact }}</td>
</tr>
</tbody>
</table>
</div>
...
...
...
</body>
</html>
sample_page_test.js
var myTestApp = angular.module("myTestModule", [])
myTestApp.controller("customerController", function ($scope, $http) {
var url = "http://192.168.1.102:8000/stl_web_app/api/customer_list/";
$http.post(url).then( function(response) {
$scope.customers = response.data;
});
});
Error Image
getting following error in Firebug console
error.png
Do i need to make any changes in settings.py of django application?
So, Can anyone please help me to solve this issue?
Any help would be greatly appreciated.
Thank you.
First of all, are you actually trying to do a POST request? Because from the looks of it, seems that you are trying to return a list of customers. Please use GET request instead of POST to fetch data.
Secondlly, If you are facing Cross-Origin Resource Sharing issue then check if you have passed correctly CSRF-TOKEN along with the POST request.
views.py
class CustomerListView(APIView):
renderer_classes = (JSONRenderer, )
def get(self, request, format=None):
content = []
customer_list = Customer_tbl.objects.all()
if customer_list:
for customer in customer_list:
content.append({
'first_name': customer.cus_first_name,
'last_name': customer.cus_last_name,
'email': customer.cus_email,
'contact': customer.cus_contact
})
return Response(content)
sample_page_test.js
var myTestApp = angular.module("myTestModule", [])
myTestApp.controller("customerController", function ($scope, $http) {
var url = "http://192.168.1.102:8000/stl_web_app/api/customer_list/";
$http.get(url).then( function(response) {
$scope.customers = response.data;
});
});
Hope this will help you.
I'm trying to create an content editable HTML table that'll update the db.sqlite3 database on keypress. The table can't have an input field in it because I also require it to be able to be filter and search using data-tables. so far I manage to retrieve the input on enter keypress but i don't know how to POST it straight to database (Presumably using AJAX) instead of JSON. Can anyone provide me with complete syntax sample as well, I'm very new to Django
Here's my code :
Model.py
class MyModel(models.Model):
a = models.CharField(max_length=10)
b = models.CharField(max_length=10)
def __str__(self):
return self.a
form.py
class MyForm(forms.ModelForm):
class Meta:
model = MyModel
fields = ['a', 'b']
view.py
def display_table(request):
context = {
"table_list": MyModel.objects.all(),
"title": "Table_List"
}
return render(request, 'tables/display.html', context)
display.html
<form action="" method="post" id="test_post">{% csrf_token %}
<div id="debug" contenteditable data-name="custom-text">Some text you can edit.</div>
<table id="myTable" class="display">
<thead>
<tr>
<th>A</th>
<th>B</th>
</tr>
</thead>
<tbody>
{% for data in table_list %}
<tr >
<td contenteditable="true" data-name="a_name" id="{{data.id}}">{{data.a}}</td>{% csrf_token %}
<td contenteditable="true" data-name="b_name" >{{data.b}}</td>{% csrf_token %}
</tr>
{% endfor %}
</tbody>
</table>
</form>
<script>
document.addEventListener('keydown', function (event) {
var esc = event.which == 27,
nl = event.which == 13,
el = event.target,
data = {};
if (esc) {
// restore state
document.execCommand('undo');
el.blur();
} else if (nl) {
// save
data[el.getAttribute('data-name')] = el.innerHTML;
// we could send an ajax request to update the field
$.ajax({
data: data,
type: "POST"
});
log(JSON.stringify(data));
el.blur();
event.preventDefault();
}
}, true);
function log(s) {
document.getElementById('debug').innerHTML = 'value changed to: ' + s;
console.log(s);
}
</script>
<script>
$(document).ready(function(){
$('#myTable').DataTable();
});
</script>
Thank you very much for everyone's help.
Yes you're right about using AJAX. A few things you will need to modify:
1. Your HTML/JS
$.ajax({
data: data,
type: "POST",
// include URL
url: 'url/to/post/to',
// include response handler here
success: function(response) {
// do whatever you want with response
// you can just console.log(response.data) first
},
error: function(response) {
// error handler to failed AJAX requests
}
});
2. Views
You'll need to change your view to return a JsonResponse instead of using render which creates an HTML response. Note that the JsonResponse will be the exact response received in the AJAX handler above.
Hope this helps.
I'd like to create dynamic input system, for example when I enter the folder name - the list of files inside automatically show up another input ChoiceField below, so I can choose the file. The methods are already written, the problem is - How can I make it in Django view?
Here is my view:
def get_name(request):
if request.method == 'POST':
form = NameForm(request.POST)
if form.is_valid():
dir_date = format_date(request.POST['date'])
files = os.listdir(os.path.join(path+dir_date))
return render(request, 'inform/show_name.html', {'data': request.POST['your_name'],
'date': format_date(request.POST['date'])})
else:
form = NameForm()
return render(request, 'inform/base.html', {'form': form})
Here is the form class:
class NameForm(forms.Form):
your_name = forms.CharField(label='Your name', max_length=100)
date = forms.DateField(widget=forms.DateInput(attrs={'class': 'datepicker'}))
flights = forms.ChoiceField(choices=?)
Finally, here is my template.
{% extends 'inform/header.html' %}
{% block content %}
<script>
$( function() {
$( ".datepicker" ).datepicker();
$( "#anim" ).on( "change", function() {
$( "#datepicker" ).datepicker( "option", "showAnim", $( this ).val() );
});
} );
</script>
<div class="container" style="color: red; size: auto;">
<form class="form-vertical" action="get_name" role="form" method="post">
{% csrf_token %}
<div class="form-group" style="display: inherit">
<center>
{{form}}
<input type="submit" value="OK">
</center>
</div>
</form>
</div>
{% endblock %}
Is there any way to dynamically read the data from the Date input and give it to the method inside the view without clicking the submit button or creating several others? If it can be solved only by ajax, jQuery or JS, could you please give me a simple sample of how it's done? I'm pretty much frustrated by the inability of creating a simple form.
Thank you in advance!
So basically you are doing it right. You already know that you need the on(change) function for the datepicker
Now as soon as the user changes a date, your on(change) function is triggered. So all you need to do now is to the get the new date value, which you already have when you do $( this ).val(). After that make an ajax call to the url corresponding to your method get_name in views.py
Something like this:
$( function() {
$( ".datepicker" ).datepicker();
$( "#anim" ).on( "change", function() {
$( "#datepicker" ).datepicker( "option", "showAnim", $( this ).val() );
send_changed_date_value(variable_with_new_date);
});
});
function send_changed_date_value(new_date) {
$.ajax({
type: // "POST" or "GET", whichever you are using
url: "/url in urls.py corresponding to get_name method in views.py/",
data: new_date,
success: function(response){
console.log("Success..!!")
}
});
}
This is how you can send the new date value to your views, everytime it is changed. If you want to submit the complete form data, i.e., your_name and flights data as well, then you may directly send serialzed data of the form in the data attribute of ajax.
Note -> You will have to return a HttpResponse from your get_name view as an ajax call requires a HttpResponse from the backend to complete the ajax call successfully. You may simply return a string in the response.
I am trying to display a list of users that get updated using AJAX at the same time a new user is added using admin page .
Django 1.9 , Python 3.5 , I am working with a windows machine
My index.html
<table class="table">
<thead>
<tr>
<th>Firstname</th>
<th>Email</th>
</tr>
</thead>
<tbody>
{% for User in users %}
<tr>
<td>{{ User.username }}</td>
<td>{{ User.email }}</td>
</tr>
{% endfor %}
</tbody>
</table>
My views.py
def index(request):
context = RequestContext(request)
users=User.objects.all()
return render_to_response('index.html',{'users':users},context)
How to implement AJAX ? Please help me how to use ajax with Django and fulfill this simple task.
Welcome to stackoverflow!
If you simply wants to call Ajax using Django then You should try this:
views.py
def index(request):
return render(request, 'index.html', locals())
def ajax_view(request):
result = dict()
data_list = []
result['status'] = "success"
for u in User.objects.all():
list_of_user = {'email': u.email, 'first_name': u.first_name}
data_list.append(list_of_user)
result['data'] = data_list
return HttpResponse(json.dumps(result), content_type='application/x-json')
index.html
<script src="/path/to/js/my_ajax.js"></script>
<table class="myTable">
<thead>
</thead>
<tbody>
</tbody>
</table>
my_ajax.js
$( document ).ready(function() {
$.ajax({
type: 'GET',
url: '/ajax/',
success: function (result) {
if (result.status == "success") {
if (result['data']) {
jQuery.each(result['data'], function (i, val) {
$('.myTable').append(
'<tr><td id="first_name">'+val['first_name']+'</td>' +
'<td id="email">'+val['email']+'</td></tr>');
});
}
}
}
})
});
urls.py
url(r'^ajax/$', ajax_view, name='temp'), # Function calls ajax
url(r'^index/$', index, name='index'), # main function redirect to index.html
This will call your ajax and get User's data.