AJAX unable to define the key's method in Django - python

First off, sorry for the odd phrasing of the title.
I currently have a webapp that allows users to order food from a resturant. In the menu html I currently have the following snippet.
{% if latest_order %}
<table class="table" id="checkout-table">
<thead class="thead-dark">
<tr>
<th scope="col"></th>
<th scope="col">YOUR</th>
<th scope="col">CART</th>
<th scope="col"></th>
</tr>
</thead>
{% for order in latest_order %}
<tr>
<td>{{ order.order_name }}</td>
<td class="change-quantity">
<form method="post">
{% csrf_token %}
<div class="row">
<div class="col-sm">
<button type="submit" name="remove_quantity" value="{{ order.id }}"
class="mr-3 btn btn-outline-info">-</button>
</div>
<div class="col-sm">
{{ order.order_quantity }}
</div>
<div class="col-sm">
<button type="submit" name="add_quantity" value="{{ order.id }}" class="ml-3 btn
btn-outline-info">+</button>
</div>
</div>
</form>
</td>
<td>${{ order.order_individual_price }}</td>
in my JS I have the following AJAX code running
$(document).ready(function(){
$(".ramen").click(function(event){
event.preventDefault()
var serializedData = $("#ramen-form").serialize()
$.ajax({
url: $("ramen-form").data("url"),
data: serializedData,
type: 'post',
success: function(response) {
$("#checkout-table").append('<tr><td>' + response.new_order.order_name + '</td><td class="change-quantity">' +
'<form method="post">{% csrf_token %}<div class="row"><div class="col-sm">' +
'<button type="submit" name="remove_quantity" value="{{ order.id }}"class="mr-3 btn btn-outline-info">-</button>' +
'</div><div class="col-sm">'+ response.new_order.order_quantity +'</div><div class="col-sm">' +
'<button type="submit" name="add_quantity" value="{{ order.id }}" class="ml-3 btn btn-outline-info">+</button>' +
'</div></div></form></td><td>$'+ response.new_order.order_individual_price +'</td><form method="post">{% csrf_token %}<th>' +
'<button type="submit" name="delete" value="{{ order.id }}" class="btn btn-danger">Delete Item</button></th></form></tr>')
}
})
});
})
In my views.py I have the following to return a JsonResponse
get_price = menu_name.Menu_price
get_desc = menu_name.Menu_Desc
new_order = Order.objects.create(
customer=request.user,
order_name=menu_name,
order_individual_price=get_price,
order_default_price=get_price,
order_desc = get_desc,
)
return JsonResponse({'new_order':model_to_dict(new_order)}, status=200)
AJAX returns the following error after I try to add an item to cart

I think the problem is you don't parse the response. So, JQuery doesn't read it becase it is a string, not JSON. You might add the following to your AJAX call to parse it automatically:
$.ajax({
...
dataType: 'json',
success: function(response) {
...
}
}
Since you're using JQuery, you might also use $.parseJSON() to parse response.

Related

How to take the value from the field and send it to the Flask code for use in the updated page

Have a good day!
I don't know much about Flask
I try to depict insert several (two) objects on the page and embed add the ability (so that you can) update these objects.
There is a main element on the page - the choice of a date range.
When you select a start date and an end date and click the button in the same way (two objects should be updated).
The first object is a table. The table (object) is updated.
The second object is a graph. This object is not updated.
What can be done to update the second object (chart)?
I would be extremely grateful for any help.
It's HTML
<div class="row">
<div class="col-md-3">
<input type="text" name="From" id="From" class="form-control" placeholder="From Date"/>
</div>
<div class="col-md-3">
<input type="text" name="to" id="to" class="form-control" placeholder="To Date"/>
</div>
<div class="col-md-6">
<input type="button" name="range" id="range" value="Range" class="btn btn-success"/>
</div>
</div>
<div id="purchase_order"></div>
<hr>
<div class="row" style="align-content: center">
<div class="text" style="align-content: center">
</div>
<div class="outer-wrapper" style="align-content: center">
<div class="table-wrapper" id="table-wrapper" style="align-content: center">
<table>
<thead>
{% for col in column_names %}
<th>{{col}}</th>
{% endfor %}
</thead>
<tbody>
{% for row in row_data %}
<tr>
{% for cell in row %}
<td>{{ cell }}</td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</div>
<div class="row">
<div class="col-md-1">
</div>
<div class="col-md-10">
<div>
<canvas id="myChart" width="800px" style="align-content: center"></canvas>
</div>
</div>
<div class="col-md-1">
</div>
</div>
it's script
<script>
$(document).ready(function (){
$.datepicker.setDefaults({
dateFormat: 'yy-mm-dd'
});
$(function (){
$("#From").datepicker();
$("#to").datepicker();
});
$('#range').click(function (){
var From = $('#From').val();
var to = $('#to').val();
if (From != '' && to != '')
{
$.ajax({
url:"/range",
method:"POST",
data:{From:From, to:to},
success:function (data)
{
$('#table-wrapper').html(data);
$('#table-wrapper').append(data.htmlresponse);
}
});
$.ajax({
url:"/range2",
method:"POST",
data:{From:From, to:to},
success:function (data)
{
$('#myChart').html(data);
$('#myChart').append(data.htmlresponse2);
}
});
}
else
{
alert("Please Select the Date")
}
});
});
</script>
it's Flask code
#app.route('/', methods=['GET','POST'])
#app.route('/index')
def home_page(): # put application's code here
if request.method=="POST":
upload_excel=request.files['upload_excel']
if upload_excel.filename != '':
filepath=os.path.join(app.config["UPLOAD_FOLDER"],upload_excel.filename)
upload_excel.save(filepath)
data=pd.read_excel(upload_excel)
data.to_sql('kotel', con=db.engine, if_exists="append", index=False)
return print(data)
df = pd.read_sql('select * from kotel', con=db.engine)
df['date'] = df['date'].dt.round('2min')
y_data = df['tnv'].tolist()
x_data = df['date'].tolist()
print(y_data)
type(y_data)
print(x_data)
df_graph = df.copy()
df_graph.drop(df_graph.columns[[0, 1, 2]], axis=1, inplace=True)
print(df_graph)
# df['date'] = pd.to_datetime(df['date'], format="%Y.%d.%B %H")
return render_template('index new.html', column_names=df.columns.values, row_data=list(df.values.tolist()), column_names_graph=df_graph.columns.values, os_y = y_data, os_x = x_data)
#app.route("/range", methods=["POST","GET"])
def range():
if request.method == 'POST':
From = request.form['From']
to = request.form['to']
df = pd.read_sql('select * from kotel', con=db.engine)
df['date'] = pd.to_datetime(df['date'])
df = df.loc[(df['date'] >= From) & (df['date'] <= to)]
df['date'] = df['date'].dt.round('2min')
return jsonify({'htmlresponse': render_template('response.html', column_names=df.columns.values, row_data=list(df.values.tolist()))}), df
#app.route("/range2", methods=["POST","GET"])
def range2():
df_new = pd.read_sql('select * from table_1', con=db.engine)
y_data = df_new['temper'].tolist()
x_data = df_new['rashod'].tolist()
return jsonify({'htmlresponse2': render_template('response2.html', os_y = y_data, os_x = x_data)})
it's extended html 1 add
<table>
<thead>
{% for col in column_names %}
<th>{{col}}</th>
{% endfor %}
</thead>
<tbody>
{% for row in row_data %}
<tr>
{% for cell in row %}
<td>{{ cell }}</td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>
it's extended html 2 add
<script>
const labels = [{% for item in os_x %}
"{{ item }}",
{% endfor %}];
const data = {
labels: labels,
datasets: [{
label: 'My First dataset',
backgroundColor: 'rgb(255, 99, 132)',
borderColor: 'rgb(255, 99, 132)',
data: [{% for item in os_y %}
{{ item }},
{% endfor %}],
}]
};
const config = {
type: 'line',
data: data,
options: {}
};
</script>
<script>
const myChart = new Chart(
document.getElementById('myChart'),
config
);
</script>
I would really like to be able (so that I can) take a value variable from a form field (dropdown ) and send it to the Flask code so that I can use it in the updated page.
image screen
image screen

how can AJAX dynamically add rows to a table

I was wondering if someone could help me figure out how to add rows to the following html dynamically using AJAX whenever a database query finds more records. I am using python flask and pandas to create a dataframe with nodes information such as when a node is ACTIVE, or in SLEEP mode, LOCKED or UNLOCKED. I was thinking that I could somehow pass that dataframe and iterate through it to create a table with that information and a link to another page for that specific node. Now,I think I have the first part down where I am POSTing the page when it is first brought up with all of the recorded nodes. But I think I'm doing that part wrong too. I suppose I have two questions then:
How can I pass a dataframe to the html and iterate through it correctly?
How can I use AJAX to add another row to the table whenever any other node that registers? I was thinking maybe I pass a list of nodeID's to the HTML when I POST and then have setInterval pass that to the python flask side, query the database, create a new list and compare..removing those that I already added, pass the dataframe of those that are new to AJAX function along with a full list of NodeID's....does that sound right?
So far I was only able to figure this out for a POST but no idea what to do next:
HTML
<div class="container">
<h2>Incubator List</h2>
<p>List of Registered Encubators:</p>
<table class="table table-dark table-striped">
<thead>
<tr>
<th>NodeID</th>
<th>Last Update</th>
<th>Status</th>
<th> </th>
<th>Control Link</th>
</tr>
</thead>
{% for node in nodes %}
<tr>
<td>{{ node.NodeID }}</td>
<td>{{ node.last_update }}</td>
{% if {{ node.Sleep }} == "True" %}
<td><p class="bg-secondary text-white text-center">SLEEP</p>></td>
{% else %}
{% if {{ node.Active }} == "True" %}
<td><p class="bg-success text-white text-center">ACTIVE</p></td>
{% else %}
<td><p class="bg-danger text-white text-center">NOT ACTIVE</p>></td>
{% endif %}
{% endif %}
{% if {{ node.LOCK }} == "True" %}
<i class="fas fa-lock"></i>
{% else %}
<i class="fas fa-unlock"></i>
{% endif %}
<td>
<form action="/nodeslist" METHOD = "POST">
<input type="hidden" id="NodeID" name="NodeID" value={{ node.NodeID }}>
<input TYPE="SUBMIT" value="Access" class = "btn btn-success">
</form>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<script>
function UPDATEnodelist(nodeIDlist) {
$.get('/nodeDHT?nodeIDlist ='+nodeIDlist ,
function(data){
const parsed = JSON.parse(data)
nodeIDlist = parsed.nodeIDlist;
something-pandas-dataframe-something;
};
)
};
setInterval(function () {
UPDATEnodelist(nodeIDlist);
return false;
}, 2500);
</script>
{% endblock content %}
python flask
#app.route('/nodeslist', methods=['POST','GET'])
def nodelist():
df= DAO.Pull_Type_Nodes()
if request.method == "POST":
title='List of Registered Nodes')
nodeIDlist = nodes.NodeID.unique()
nodes = df.to_json(orient ='records')
return render_template('nodeslist.html',title=title, nodes=nodes, nodeIDlist=nodeIDlist)
else:
oldnodeIDlist = request.form['NodeID']
add_df = df[~df['NodeID'].isin(oldnodeIDlist)]
new_nodes = add_df.to_json(orient ='records')
return new_nodes,nodeIDlist
Please any help would be greatly appreciated!
EDIT:
The response should be a dataframe with fields 'nodeID','sleep' (bool), 'lock' (bool), 'active' (bool)
<table id="table" class="table table-dark table-striped">
<thead>
<tr>
<th>NodeID</th>
<th>Last Update</th>
<th>Status</th>
<th></th>
<th>Control Link</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<form action="/nodeslist" METHOD="POST">
<input type="hidden" id="NodeID" name="NodeID" value={{ node.NodeID }}>
<input TYPE="SUBMIT" value="Access" class="btn btn-success" id="btn">
</form>
</td>
</tr>
</tbody>
</table>
const date = new Date();
const data = [...Array(10).keys()].map(id => {
return {
id: id+1,
date: new Date((Math.random() * 10000000) + date.getTime()).toLocaleString(),
status: Math.floor(Math.random() * 2),
};
});
const tbody = document.querySelector('#table').querySelector('tbody');
function test(evt) {
evt.preventDefault();
let fragment = document.createDocumentFragment();
data.forEach(d => {
let tr = document.createElement('tr');
Object.keys(d).forEach(x => {
let td = document.createElement('td');
let textNode = document.createTextNode(d[x]);
td.appendChild(textNode);
tr.appendChild(td);
})
fragment.appendChild(tr);
});
tbody.appendChild(fragment);
}
document.querySelector('#btn').onclick = test;
Here working example

Upload unknown numbers (dynamically decided) of files under Django framework

I encountered an issue: if I want to apply this dynamically rows adding bootstrap code(ref here bootstrap) , I won't be knowing how many files user will upload in advance.(Although I define a maximum of numbers of files allowed to be uploaded:10)
I am using Django 2.1.5.
I have tried to write something like UploadFileForm in form.py, but in that way, I needed to write exactly 10 form.Charfield inside the class, which I am not willing to see.
<form action="" method="post" enctype="multipart/form-data" id="bookform">
{% csrf_token %}
<table id="createBookTable" class=" table order-list">
<thead>
<tr>
<td>book title(in original lang.)</td>
<td>author(in original lang.)</td>
<td>book title(in Eng.)</td>
<td>author(in Eng.)</td>
<td>book image</td>
</tr>
</thead>
<tbody>
<tr style="display:none">
<td colspan="5" style="text-align: left;" >
<input type="text" id="counter" name="counter" value=""/>
</td>
</tr>
<tr class="bookTr" id="bookTr-0">
<td class="col-sm-3">
<input type="text" name="orginBookname0" class="form-control" />
</td>
<td class="col-sm-3">
<input type="mail" name="originAuthor0" class="form-control"/>
</td>
<td class="col-sm-3">
<input type="text" name="engBookname0" class="form-control"/>
</td>
<td class="col-sm-3">
<input type="text" name="engAuthor0" class="form-control"/>
</td>
<td>
<input type="file" name="bookimg0">
</td>
<td class="col-sm-1"><a class="deleteRow"></a>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="5" style="text-align: left;">
<input type="button" class="btn btn-lg btn-block " id="addrow" value="Add Row" />
</td>
</tr>
<tr>
<td colspan="5" style="text-align: left;">
<input type="submit" name="button" id="bookSubmitBtn" class="btn btn-lg btn-block btn-beautiful" value="Submit">
</td>
</tr>
</tfoot>
</table>
</form>
These are modified version of the mentioned bootstrap demo example:
var counter = 0;
$("#counter").prop('value',counter);
$("#addrow").on("click", function () {
if(counter<=9){
counter++;
var newRow = $('<tr class="bookTr" id="bookTr-'+counter+'">');
var cols = "";
cols += '<td><input type="text" class="form-control" name="orginBookname' + counter + '"/></td>';
cols += '<td><input type="text" class="form-control" name="originAuthor' + counter + '"/></td>';
cols += '<td><input type="text" class="form-control" name="engBookname' + counter + '"/></td>';
cols += '<td><input type="text" class="form-control" name="engAuthor' + counter + '"/></td>';
cols += '<td><input type="file" name="bookimg' + counter + '"/></td>';
cols += '<td><input type="button" class="ibtnDel btn btn-md btn-danger " value="Delete"></td>';
newRow.append(cols);
$("table.order-list").append(newRow);
$("#counter").prop('value',counter);
}
else{
alert("You can only add 10 books per time.");
}
});
The expected results would be that all files chosen by the users be uploaded to media\photos folder. Again, we are not able to know in advance how many files they will be uploading.
I want to use ajax call at the front-end under Django framework.
I think you are looking for Formsets. You use django formset to dynamically render and upload any number of form fields. check it out here https://github.com/elo80ka/django-dynamic-formset
I found a way to avoid using form.py but using ajax call.
In settings.py
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
In urls.py
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
In models.py
class book(models.Model):
titleOrigin = models.CharField(max_length=200,null = False)
authorOrigin = models.CharField(max_length=100,null = True)
titleEnglish = models.CharField(max_length=200,null = True)
authorEnglish = models.CharField(max_length=100,null = True)
bookImgFname = models.CharField(max_length=300,null=True)
In createbook.js(use FormData() function!!!):
function upload(event) {
event.preventDefault();
var formdata = new FormData($('#bookform').get(0));
$.ajax({
url: '/createbook/',
type: 'post',
data: formdata,
cache: false,
processData: false,
contentType: false,
success: function(data) {
alert('success');
}
});
return false;
}
$(function() {
$('#bookform').submit(upload);
});
In views.py, use FileSystemStorage and request.FILES['bookimg'+str(i)](thanks to this tutorial)
def createbook(request):
if request.method == 'POST' and request.is_ajax():
for i in range(int(request.POST.get('counter'))+1): **#the nondisplayed counter is a trick**
curOrginBookname = request.POST.get('orginBookname'+str(i))
curOriginAuthor = request.POST.get('originAuthor'+str(i))
curEngBookname = request.POST.get('engBookname'+str(i))
curEngAuthor = request.POST.get('engAuthor'+str(i))
curBookimg = request.FILES['bookimg'+str(i)]
fss = FileSystemStorage()
concatenatedFname = curOrginBookname+"_"+curBookimg.name
fss.save("photos\\"+concatenatedFname, curBookimg)
bookToBeSaved = book(titleOrigin=curOrginBookname,authorOrigin=curOriginAuthor,
titleEnglish=curEngBookname,authorEnglish=curEngAuthor,bookImgFname=concatenatedFname)
bookToBeSaved.save()
return HttpResponse('')
else:
return render(request, "createbook.html", locals())
remember to import this:
from django.core.files.storage import FileSystemStorage

Reverse for `view` with arguments '('',)' not found. 1 pattern(s) tried: `[u'bms/update/(?P<id>[0-9]+)/$']`

This is my update view which I'm using to get pre-populated form. Although this is also not working.
def update(request, id):
item = get_object_or_404(BookEntry, id=id)
if request.method=="POST":
form = UpdateForm(request.POST, instance=item)
if form.is_valid():
post=form.save(commit=False)
post.save()
return HttpResponseRedirect(reverse('bms:index'), id)
else:
form=EntryForm(instance=item)
return HttpResponseRedirect(reverse('bms:index'), id)
return render(request, 'index.html', {'form':form})
This is my urls.py
url(r'^update/(?P<id>[0-9]+)/$', views.update, name='update'),
This is the error that I'm getting again and again:
NoReverseMatch at /bms/
Reverse for 'update' with arguments '('',)' not found. 1 pattern(s) tried: [u'bms/update/(?P[0-9]+)/$']
I'm not sure if passing the url in right way. This is what i'm doing:
<form action="{% url 'bms:update' book.id %}" id="updateform" name="updateform" method="POST">
When I look at traceback, it's showing something's wrong in above line and this line:
return render(request, "bms/index.html", context)
This is my index view:
def index(request):
context = {}
book_detail = BookEntry.objects.all()
context.update({
'book_detail': book_detail
})
response = {"status": False, "errors": []}
if request.is_ajax():
id = request.POST['id']
csrf_token = request.POST['csrfmiddlewaretoken']
response = {}
response['status'] = False
book = BookEntry.objects.filter(id=id).first()
context = {
"book": book,
"csrf_token": csrf_token
}
template = render_to_string("bms/index.html", context)
response['template'] = template
response['status'] = True
return HttpResponse(json.dumps(response), content_type="applicaton/json")
return render(request, "bms/index.html", context)
My index.html:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="//fonts.googleapis.com/css?family=Raleway">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.15.1/jquery.validate.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script>
function update_entry(id) {
var id = id
$.ajax({
url: "{% url 'bms:index' %}",
type: "POST",
data:{
'csrfmiddlewaretoken': '{{ csrf_token }}',
'id' : id,
},
success: function(response){
$("#updateform").modal("show");
}
});
}
function update_property(id) {
window.location.replace("/bms/update" + id+"/");
}
</script>
<style>
body{
font-family: Raleway;
}
</style>
</head>
<body>
<div class="container">
<div class="page-header">
<h1>Details of Books</h1>
</div>
<table class = "table table-bordered table-hover">
<tr>
<th>S No.:</th>
<th>Title:</th>
<th>Author:</th>
<th>Edition:</th>
<th>Publisher:</th>
<th>Genre:</th>
<th>Detail:</th>
<th>Language:</th>
<th>Price:</th>
<th>ISBN:</th>
<th>Action:</th>
</tr>
{% for item in book_detail %}
<tr>
<td>{{ forloop.counter }}</td>
<td>{{ item.title }}</td>
<td>{{ item.author }}</td>
<td>{{ item.edition }}</td>
<td>{{ item.publisher }}</td>
<td>{{ item.genre }}</td>
<td>{{ item.detail }}</td>
<td>{{ item.language }}</td>
<td>{{ item.price }}</td>
<td>{{ item.isbn }}</td>
<td>
<a data-href="bms:update({{item.id}})" onclick="update_entry({{item.id}})" class="btn btn-warning" data-toggle="modal">
<span class = "glyphicon glyphicon-pencil"></span> Edit
</a>
</td>
</tr>
{% endfor %}
</table>
<div class="modal fade" id="updateform" role="dialog">
<div class="modal-dialog">
<div class = "modal-content">
<div class = "modal-header">
<button type = "button" class = "close" data-dismiss="modal">×</button>
<h3 class="modal-title">
<b>Update Details</b>
</h3>
</div>
<div class = "modal-body">
<form action="{% url 'bms:update' book.id %}" id="updateform" name="updateform" method="POST">
{% csrf_token%}
<div class = "form-group">
<label for = "title">
Title:
</label>
<input class = "form-control" id="book_title" type = "text" name="title" value="{{ book.title }}">
</div>
<div class="form-group">
<label for = "author">
Author:
</label>
<input id="book_author" class = 'form-control' type = "text" name="author" value="{{ book.author }}">
</div>
<div class = "form-group">
<label for = "edition">
Edition:
</label>
<input id="book_edition" type = "text" class = 'form-control' name="edition" value="{{ book.edition }}">
</div>
<div class = "form-group">
<label for ="publisher">
Publisher:
</label>
<input id="book_publisher" type = "text" name="publisher" class = 'form-control' value="{{ book.publisher }}"/>
</div>
<div class = "form-group">
<label for ="genre">
Genre:
</label>
<input id="book_genre" type = "text" name="genre" class = 'form-control' value="{{ book.genre }}"/>
</div>
<div class = "form-group">
<label for ="language">
Language:
</label>
<input id="book_language" type = "text" name="language" class = 'form-control' value="{{ book.language }}"/>
</div>
<div class = "form-group">
<label for ="price">
Price:
</label>
<input id="book_price" type = "text" name="price" class = 'form-control' value="{{ book.price }}"/>
</div>
<div class = "form-group">
<label for ="isbn">
ISBN:
</label>
<input id="book_isbn" type = "text" name="isbn" class = 'form-control' value="{{ book.isbn }}"/>
</div>
<input type = "submit" value="Update" id="update" class = "btn btn-success" style="font-size:18px;" />
</form>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
Does the BookEntry model have a primary key column? I started having the same error when I added a primary key field on the model the id was referencing. Apparently the id column is replaced by the primary key field. I removed the key and migrated the changes.The error is gone now.

Django Ajax get request - load model instance into a form

I have a table in a HTML template that displays all instances of a django model. on each row of the template I have an edit button that looks up the primary key of each instance, and by clicking that button I want all the fields in the model instance to be populated in a modal by using ajax. After that I want to be able to edit the data and use ajax to send the edited data back to the database.
I have been searching all over the web and found this post that is exactly what I need, but I still can't get it to work. Any help would be greatly appreciated.
jQuery code
var modalDiv = $("#modal-div");
$(".open-modal").on("click", function() {
console.log("button clicked");
var url = $(this).attr('data-url').replace('/', '');
console.log("url:",url); // this returns my customer number but is not used in the code below
$.ajax({
url: $(this).attr("data-url"),
type: 'get',
success: function(data) {
console.log("success");
modalDiv.html(data);
$("#myEdit").modal(); //#myEdit is the ID of the modal
},
error : function() {
console.log("Error: this did not work"); // provide a bit more info about the error to the console
}
});
});
a tag in form
<a class="btn open-modal" data-url="{% url 'dashboard:customer_update' kunde.kundenr %}">Edit</a>
Needless to say, I keep receiving the error console.log message.
Below is the complete codebase.
Model:
class Kunde(models.Model):
avd = [('610','610'), ('615', '615'), ('620', '620'), ('625', '625'), '630', '630'), ('635', '635'),('640', '640'),('645', '645'), ('650', '650'), ('655', '655')]
avdeling = models.CharField(max_length=3, choices=avd)
selskap = models.CharField(max_length=50, unique=True)
kundenr = models.CharField('Kundenummer', max_length=15, unique=True, primary_key=True)
gatenavn = models.CharField(max_length=50,)
postnr = models.CharField('Postnummer', max_length=4)
poststed = models.CharField(max_length=30)
kommune = models.CharField(max_length=30)
timestamp = models.DateField(auto_now_add=True)
updated = models.DateField(auto_now=True)
def get_absolute_url(self):
return reverse("dashboard:index")
def __str__(self):
return self.selskap
class Meta:
ordering = ['selskap']
Urls
app_name = "dashboard"
urlpatterns = [
path('', views.dashboard, name='index'),
path('', views.customer_list, name='customer_list'),
url(r'^(?P<kundenummer>[0-9]+)$', views.customer_update, name='customer_update'),
]
Views:
main view to display the table
def dashboard(request):
template = 'dashboard/index.html'
if request.user.groups.filter(name__in=['Vest']).exists():
queryset = Kunde.objects.filter(Q(avdeling='630') | Q(avdeling='635')).all()
elif request.user.groups.filter(name__in=['Nord']).exists():
queryset = Kunde.objects.filter(Q(avdeling='610') | Q(avdeling='615') | Q(avdeling='620')).all()
elif request.user.groups.filter(name__in=['Øst']).exists():
queryset = Kunde.objects.filter(Q(avdeling='660') | Q(avdeling='655') | Q(avdeling='650')).all()
elif request.user.groups.filter(name__in=['Sør']).exists():
queryset = Kunde.objects.filter(Q(avdeling='640') | Q(avdeling='645')).all()
elif request.user.groups.filter(name__in=['Nord-Vest']).exists():
queryset = Kunde.objects.filter(Q(avdeling='625')).all()
else:
queryset = Kunde.objects.all()
context = {
"object_list": queryset,
}
return render(request, template, context)
view to display the modal with
def customer_update(request, kundenr=None):
template = 'dashboard/index.html'
instance = get_object_or_404(Kunde, kundenr=kundenr)
context={
'selskap': instance.selskap,
'instance': instance,
}
return render(request, template, context)
HTML table
<div class"container-table" style="overflow-x:auto;">
<table class="display table table-bordered table-condensed" id="table_kundeliste">
<thead class="thead-inverse">
<tr>
<th>Avdeling</th>
<th>Selskap</th>
<th>Kundenr.</th>
<th>Poststed</th>
<th>Kommune</th>
<th>Rediger</th>
</tr>
</thead>
<tbody>
{% for kunde in object_list %}
<tr>
<td> {{ kunde.avdeling }} </td>
<td> {{ kunde.selskap }} </td>
<td> {{ kunde.kundenr }} </td>
<td> {{ kunde.poststed }} </td>
<td> {{ kunde.kommune }} </td>
<td>
<a class="btn open-modal" data-url="{% url 'dashboard:customer_update' kunde.kundenr %}">Edit</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
this part include modal in html
<div id="modal-div" class="modal-div">
{% include 'dashboard/customer-modal.html' %}
</div>
this is the modal template itself
<div class="modal fade" id="myEdit" role="dialog">
<div class="modal-dialog">
<form class="well contact-form" method="post" action="{% url dashboard:'customer_update'}">
{% csrf_token %}
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<label for="avdeling">Avdeling:</label>
<input type="text" class="form-control" required="" name="avdeling" value="{{ instance.avdeling }}" id="avdeling">
<label for="selskap">Selskap:</label>
<input type="text" class="form-control" required="" name="selskap" value="{{ instance.selskap }}" id="selskap">
<label for="kundenummer">Kundenummer:</label>
<input type="text" class="form-control" required="" name="kundenummer" value="{{ instance.kundenr }}" id="kundenummer">
<label for="gatenavn">Gatenavn:</label>
<input type="text" class="form-control" required="" name="gatenavn" value="{{ instance.gatenavn }}" id="gatenavn">
<label for="postnummer">Postnummer:</label>
<input type="text" class="form-control" required="" value="{{ instance.postnr }}" name="postnummer" id="postnummer" >
<label for="poststed">Poststed:</label>
<input type="text" class="form-control" required="" value="{{ instance.poststed }}" name="poststed" id="poststed" >
<label for="kommune">Kommune:</label>
<input type="text" class="form-control" required="" value="{{ instance.kommune }}" name="kommune" id="kommune" >
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-default">Valider</button>
<button value="" type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</form>

Categories