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
Related
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.
Background:
I'm fairly new to developing front end and the Flask module in Python. I am difficulty updating the same page.
What I want to achieve:
There are three parts to what I want to achieve
Part/Step 1: I can create a form such as the one below
Part/Step 2: When the form is filled in as below, and the [verify] button is hit it goes to Step 3
Part/Step 3: Once the verify button is hit, just underneath it the information that was passed gets placed underneath it. There are also two buttons, with [commit] and [cancel] button. If [cancel] is hit, the site resets to as it were in Step 1. If [commit] is hit, it goes to a different website in step 4
Part/Step 4: If [commit] is hit from the image above, another site is retrieved with the following message.
Note:
Happy to share my code, but I just have the empty form in step 1. I can't proceed after that. As mentioned, I'm very new to front end stuff.
Update:
I'm having difficulties with 2 things currently:
When I click [cancel], the whole form shifts to the left (How can I make it centered?)
How can I print multiple things (ideally in a centered table) after hitting the [verify] button
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
document.getElementById("verify").style.display = "none";
document.getElementById("committed").style.display = "none";
})
function onVerify() {
document.getElementById("verifyName").innerHTML = 'First Name: ' + document.getElementById("first_name").value
document.getElementById("verify").style.display = "block";
}
function onCommit() {
document.getElementById("form").style.display = "none";
document.getElementById("verify").style.display = "none";
document.getElementById("committed").style.display = "block";
}
function onCancel() {
document.getElementById("form").style.display = "block";
document.getElementById("verify").style.display = "none";
document.getElementById("name").value = ""
}
</script>
<style>
h3 {text-align: center;}
.right {
text-align: right;
margin-right: 1em;
}
.center {
display: flex;
justify-content: center;
align-items: center;
}
</style>
</head>
<h3>Personnel Details</h3>
<div class="center" id="form">
<table>
<tr>
<td class="right">
<label>Salutation:</label>
</td>
<td>
<select name="gender">
<option value=""></option>
<option value="male">Mr.</option>
<option value="female">Ms.</option>
</select>
</td>
</tr>
<tr>
<td class="right">
<label>First Name:</label>
</td>
<td>
<input id="first_name">
</td>
</tr>
<tr>
<td class="right">
<label>Middle Name:</label>
</td>
<td>
<input id="middle_name">
</td>
</tr>
<tr>
<td class="right">
<label>Last Name:</label>
</td>
<td>
<input id="last_name">
</td>
</tr>
<tr>
<td class="right">
<label>Email:</label>
</td>
<td>
<input id="email">
</td>
</tr> <tr>
<td class="right">
<label>DOB:</label>
</td>
<td>
<input type="date" name="issue_date" value="" min="1900-01-01" max="2100-12-31">
</td>
</tr>
<tr>
<td>
</td>
<td class="center">
<div>
<button onclick="onVerify()">Verify</button>
</div>
</td>
</tr>
</table>
</div>
<div id="verify">
<div id="verifyName">
</div>
<button onclick="onCommit()">Commit</button>
<button onclick="onCancel()">Cancel</button>
</div>
<div id="committed">
Committed! :)
</div>
</html>
This is just the minimal code, I have used to just give an idea, how to achieve the similar behavior, with just one input field. You can easily extend this with other fields.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script>
$(document).ready(function() {
document.getElementById("verify").style.display = "none";
document.getElementById("committed").style.display = "none";
})
function onVerify() {
document.getElementById("verifyName").innerHTML = 'First Name: ' + document.getElementById("name").value
document.getElementById("verify").style.display = "block";
}
function onCommit() {
document.getElementById("form").style.display = "none";
document.getElementById("verify").style.display = "none";
document.getElementById("committed").style.display = "block";
}
function onCancel() {
document.getElementById("form").style.display = "block";
document.getElementById("verify").style.display = "none";
document.getElementById("name").value = ""
}
</script>
<div id="form">
<label> First Name:
<input id="name">
</label>
<div>
<button onclick="onVerify()">Veryfy</button>
</div>
</div>
<div id="verify">
<div id="verifyName">
</div>
<button onclick="onCommit()">Commit</button>
<button onclick="onCancel()">Cancel</button>
</div>
<div id="committed">
Committed! :)
</div>
Basically I am using matplotlib to generate charts that I want to then display directly to the user. The user fills out a form and the variables are passed to a few methods that create the chart. The code I currently have will show only the image and get rid of the form. Is it possible to display the image on the page so that the user can modify the queries/connections and see the results with each subsequent form submission?
Here is my code:
from flask import Flask, request, render_template, send_file, redirect, url_for
import flask
import MultipleDatabasesLib as mdl
import subprocess
import pandas as pd
import matplotlib as plt
from matplotlib import pyplot as plt
app = Flask(__name__)
xlabel = ""
ylabel = ""
graph_title = ""
#app.route('/')
def my_form():
return render_template('my-form.html')
#app.route('/get_form_vals', methods=['POST', 'GET'])
def form_vals():
df = pd.DataFrame()
df_group = pd.DataFrame()
fig_size = plt.rcParams["figure.figsize"]
fig_size[0] = 15
fig_size[1] = 12
plt.rcParams["figure.figsize"] = fig_size
base = "C:/Python36-32/GraphFactory/Final_csv.csv"
conn1 = flask.request.args.get('conn1')
conn2 = flask.request.args.get('conn2')
sql1 = flask.request.args.get('sql1')
sql2 = flask.request.args.get('sql2')
charttype = flask.request.args.get('charttype')
xlabel = flask.request.args.get('xLabel')
ylabel = flask.request.args.get('yLabel')
groupBy = flask.request.args.get('groupBy')
#graph_title = charttype + "Chart"
mdl.gen_csv(conn1, conn2, sql1, sql2)
df = pd.read_csv(base)
df_group = df.groupby(['YR', 'INSTANCE']).size()
if charttype == "bar":
mdl.bar_plot(xlabel, ylabel, 'Plot', df_group)
elif charttype == "pie":
mdl.pie_plot(xlabel, ylabel, 'Plot', df_group)
elif charttype == "line":
mdl.line_plot(xlabel, ylabel, 'Plot', df_group)
elif charttype == "hist":
mdl.hist_plot(xlabel, ylabel, 'Plot', df_group)
#return send_file("plt.png", mimetype='image/gif')
return flask.jsonify({"result":"<div class='user_avatar' style='background-image:url('/static/images/figure.png');width:240px;height:240px;background-size:cover;border-radius:10px;'>"})
app.run(host='0.0.0.0', port=33)
HTML:
<!DOCTYPE html>
<html lang="en">
<link rel="stylesheet" href="/static/my-css.css">
<head>
<meta charset="UTF-8">
<title>Graph Factory</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<table class="headerTable" background="https://crunchify.com/bg.png" width="100%">
<tr>
<td width="95%"><img src="static/SEILogo.png" /></td>
</tr>
</table>
<table style="width:50%" class="inputForm" align="center" cellspacing="0">
<tr>
<th>
Connection
</th>
<th>
Query
</th>
</tr>
<tr>
<td align="center">
<input type="text" name="conn1" id="conn1"/>
</td>
<td align="center">
<textarea name="sql1" cols="70" rows="8" id="sql1"></textarea>
</td>
</tr>
<tr>
<td align="center">
<input type="text" name="conn2" id="conn2"/>
</td>
<td align="center">
<textarea name="sql2" cols="70" rows="8" id="sql2"></textarea>
</td>
{#<td align="left">
Export CSV
</td>#}
</tr>
<tr class="top row">
<td align="center">
<label>X-axis Label</label>
</td>
<td align="center">
<input type="text" name="xLabel" id="xLabel"/>
</td>
</tr>
<tr>
<td align="center">
<label>Y-axis Label</label>
</td>
<td align="center">
<input type="text" name="yLabel" id="yLabel"/>
</td>
</tr>
<tr>
<td align="center">
<label>Group by Parameter</label>
</td>
<td align="center">
<input type="text" name="groupBy" id="groupBy"/>
</td>
</tr>
<tr>
<td align="center">
<label>Graph Type</label>
</td>
<td align="center">
<select name="charttype" id="dropdownchart">
<option value="bar">Bar</option>
<option value="pie">Pie</option>
<option value="line">Line</option>
<option value="hist">Hist</option>
</select>
</td>
</tr>
<tr>
<td colspan="20" align="center">
<button type='button' class='get_result'>Show Graph</button>
</td>
</tr>
</table>
<div id='image_location'></div>
<script>
$(document).ready(function() {
$('.get_result').click(function(){
var conn1 = $('#conn1').val();
var conn2 = $('#conn2').val();
var sql1 = $('#sql1').val();
var sql2 = $('#sql2').val();
var xlabel = $('#xLabel').val();
var ylabel = $('#yLabel').val();
var groupBy = $('#groupBy').val();
var dropdownchart = $('#dropdownchart').val();
$.ajax({
url: "/get_form_vals",
type: "get",
data: {conn1: conn1, conn2:conn2, sql1:sql1, sql2:sql2, xlabel:xlabel, ylabel:ylabel,
groupBy:groupBy, dropdownchart:dropdownchart},
success: function(img) {
$("#image_location").html(img.result);
},
error: function(xhr) {
print("error")
}
});
});
});
</script>
</body>
</html>
You will have to use flask with ajax. To do that, you will need to create a separate route to create the graph, savee the file, and return the HTML with the link to the image. Below is a slightly shortened solution showing how this can be done. Ensure that you have a static/images directory created, with static at the same level as templates/ in your application folder:
in main_app.py:
import matplotlib.pyplot as plt
import flask
app = flask.Flask(__name__
#app.route('/', methods=['GET'])
def home():
return render_template('my-form.html')
#app.route('/get_form_vals')
def form_vals():
conn1 = flask.request.args.get('conn1')
conn2 = flask.request.args.get('conn2'])
#rest of vals follow
plt.plot(x, y) #formulate your x, y values before
plt.savefig('/app/static/images/filenameXYZ.png') #save to the images directory
return flask.jsonify({"result":"<div class='user_avatar' style='background-image:url('/static/images/figure.png');width:240px;height:240px;background-size:cover;border-radius:10px;'>"})
Then, in my-form.html:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<input type='text' id='conn1'>
<input type='text' id='conn2'>
<!--rest of inputs follow -->
<button type='button' class='get_result'></button>
<div id='image_location'></div>
<script>
$(document).ready(function() {
$('.get_result').click(function(){
var conn1 = $('#conn1').val();
var conn2 = $('#conn2').val();
//get the rest of the vals
$.ajax({
url: "/get_form_vals",
type: "get",
data: {conn1: conn1, conn2:conn2}, //fill out rest of object
success: function(response) {
$("#image_location").html(response.message);
},
error: function(xhr) {
//Do Something to handle error
}
});
});
});
</script>
</html>
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>
This is the HTML:
<form method="post" action="./xxxxx" name="form1">
<input type="hidden" name="requestKey" value="52032a76cf53340b07052fd143feddc4a9d8f18130c80ec86003ab56e0d91b36"/>
<input type="hidden" name="option" value="txnlist">
<input type="hidden" name="account" value='1336169999'>
<input type="hidden" name="app" value="D">
<input type="hidden" name="lockType" value="">
<p><span class="header2"> Statement options </span>
<table summary="" width="100%" border="0" cellpadding="1" cellspacing="1">
<tr>
<td width="20"></td>
<td width="20"><input type="radio" name="optDateFilter" value="1"></td>
<td>Transactions for the last 30 days</td>
<td></td>
</tr>
<tr>
<td width="20"></td>
<td width="20"><input type="radio" name="optDateFilter" value="2"></td>
<td>Transactions for the last 90 days</td>
<td></td>
</tr>
<tr>
<td width="20"> </td>
<td width="20"><input type="radio" name="optDateFilter" checked='checked' value="3" style="vertical-align: middle"></td>
<td>
<div>
<font style="vertical-align: middle;">Transactions from </font>
<script src='jquery/js/ui/min/jquery.ui.datepicker.min-1.8.10.js'></script>
<script type='text/javascript'>$(function() {$('#datepicker1').datepicker( { changeMonth : true, changeYear : true, dateFormat : 'dd/mm/yy', showOn: 'both', buttonImage: 'images/calendar.png', buttonImageOnly: true }); }); </script>
<input type='text' id='datepicker1' name='txtFromDate' size='11' maxlength='10' value='14/12/2012' onchange="checkFromDate(document.form1.txtFromDate.value);document.form1.optDateFilter[2].checked = true;">
<font style="vertical-align: middle;">to</font>
<script type='text/javascript'>$(function() {$('#datepicker2').datepicker( { changeMonth : true, changeYear : true, dateFormat : 'dd/mm/yy', showOn: 'both', buttonImage: 'images/calendar.png', buttonImageOnly: true }); }); </script>
<input type='text' id='datepicker2' name='txtToDate' size='11' maxlength='10' value='01/01/2013' onchange="checkToDate(document.form1.txtFromDate.value,document.form1.txtToDate.value);document.form1.optDateFilter[2].checked = true;">
</div>
</td>
<td><font style="font-size: 8pt; vertical-align: middle;"><i>(maximum date range 3 months)</i></font></td>
</tr>
</table>
<table summary="" cellpadding="1" cellspacing="1" border="0">
<tr>
<td width="20"> </td>
<td width="20">
<a href="javascript:if(document.form1.optDateFilter[2].checked==true){CheckAndSubmit(document.form1.txtFromDate.value,document.form1.txtToDate.value);}else{showOverlay();document.form1.submit();};">
<img src="images/proceed.gif" alt="Show the selected range of transactions" border="0" width="22" height="22" />
</a>
</td>
<td>
Show the selected range of transactions
</td>
</tr>
</table>
</form>
This is the code i have, and it is not working:
self.browser.select_form('form1')
self.browser.form.set_all_readonly(False)
self.browser['txtFromDate'] = '28/12/12'
self.browser['txtToDate'] = '01/01/13'
resp = self.browser.submit()
html = resp.read()
I figured that i had to do this
self.browser.select_form('form1')
self.browser['optDateFilter'] = ['2']
self.browser.form.find_control(name="txtFromDate", id="datepicker1").value = "13/10/12"
self.browser.form.find_control(name="txtToDate", id="datepicker2").value = "01/01/13"
resp = self.browser.submit()
mechanize has a strange quirk: since there can be multiple radio button elements in a HTML document with the same name it insists that you use a list as value, even though only a single radio button may be selected at any time. That means that you need to use this:
self.browser.form.find_control(name='optDateFilter').value = ['2']
The same holds for checkboxes where it makes more sense because a user is allowed to select multiple values.