Django pop up modal after Inserting/updating data - python

I've been searching in google and SO about pop up message when user submit but that doesnt work when i apply it to my code, I just want that if the user update/insert data, a pop up modal message appears
I have this form in my html
<form method="post" id="myform" class="myform" style="width: 100%" enctype="multipart/form-data">{% csrf_token %}
<table id="blacklistgrids" border="2px">
<tr>
{% for v in table.0 %}
{% if forloop.first %}
<th id="thupdate">{{v}}</th>
{% else %}
<th ><input type="text" name="updatedate" value="{{ v }}"></th>
{% endif %}
{% endfor %}
<th hidden></th>
<th data-id='headerss' id='headerave'>Average</th>
</tr>
<tbody>
{% for row in table|slice:"1:" %}
<tr class="tr2update">
<td><input type="text" value="{{row.0}}" name="students" hidden>{% for n in teacherStudents %}{{n.Students_Enrollment_Records.Student_Users}}{% endfor %}</td>
<td class="tdupdate" hidden><input type="text" hidden></td>
{% for teacher in students %}
<input type="hidden" name="id" value="{{teacher.id}}"/>
<td>
<input type="text" data-form-field="{{teacher.id}}" name="oldgrad" class="oldgrad" value="{{teacher.Grade|floatformat:'2'}}"/>
</td>
{% endfor %}
{% for avg in average %}
<td data-id='row' id="ans"><input type='number' class='averages' step="any" name="average" value="{{average.average_grade|floatformat:'2'}}" readonly/></td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>
<div class="buttons">
<input type="submit" value="&nearrow; Update" class="save" formaction="/updategrades/">
</div>
</form>
<script>
if (typeof jqXhr.success != 'undefined') {
$('#thanksModal').modal('show');
} else {
$('#myform').html(jqXhr);
}
</script>
and this is my views.py
import json
def updategrades(request):
/some logic/
return HttpResponse(json.dumps({"success":True}), content_type="application/json")

you could use ajax and bootstrap modal,
crate a general modal somewhere in your html page(I usually have it in my base.html so it will be included in all pages) then submit your from by using ajax then ajax will provide success or error function regarding the response will receive from server-side. put that message in the modal. an example is:
somewhere inside base.html
<!-- Info General modal -->
<div id="general_modal" class="modal fade " >
<div class="modal-dialog ">
<div class="modal-content ">
<div class="modal-header bg-info">
<h6 class="modal-title">Info header</h6>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
<!-- Empty will be field by Js -->
</div>
</div>
</div>
</div>
<!-- /info General modal -->
js and ajax function
$("#your-form").on('submit',function(e){
e.preventDefault();
var ajax_link = this.getAttribute("data-ajax-link");
var target = this.getAttribute("data-target");
var title = this.getAttribute("data-modal-title");
var size = this.getAttribute("data-modal-size");
var bg = this.getAttribute("data-modal-content-bg");
// $(target+" .modal-body").load(ajax_link);
$.ajax({
url:ajax_link,
type:'POST',
// data: $("#your-form-feilds").serialize(),
success: function (response){
$(target+" .modal-body").html(response);
},
/*
error:function (response){
new PNotify({
title: 'oops',
text:' Unable to load',
type: 'error'
});
}
*/
});
$(target+" .modal-content").addClass(bg);
$(target+" .modal-title").html(title);
$(target+" .modal-dialog").removeClass().addClass("modal-dialog");
$(target+" .modal-dialog").addClass(size);
});
html form
<form action="." method="post" id="your-form" class="btn btn-info modal-ajax-load"
data-ajax-link="url"
data-toggle="modal"
data-modal-title="tilte"
data-target="#general_modal">
ofcurse you need to modify this answer to create the functions you need

Related

How to create a dynamic dropdown in Flask?

All the questions I referred to on SO were displaying results of creating a dynamic dropdown where they made use of database, I am not making use of a database but making use of a CSV file to fetch data, so those answers couldn't help me
here is my app.py file
#app.route('/StatsPage', methods=['GET','POST'])
def StatsPage():
timeline=['Daily', 'Weekly', 'Monthly']
return render_template('StatsPage.html', timeline=timeline)
#app.route('/StatsPage/timing', methods=['GET','POST'])
def get_timeline(timing):
dates_dict=['2020-08-23', '2020-08-24', '2020-08-25', '2020-08-26', '2020-08-27', '2020-08-28', '2020-08-29', '2020-08-30', '2020-08-31', '2020-09-01', '2020-09-02', '2020-09-03', '2020-09-04', '2020-09-05', '2020-09-06', '2020-09-07', '2020-09-08', '2020-09-09']
months=['August', 'September']
week=['2020-08-23', '2020-08-30', '2020-09-06', '2020-09-13', '2020-09-20']
timelines={
'Daily': dates_dict,
'Weekly': week,
'Monthly': months
}
return jsonify(timelines[timing])
Here is my StatsPage.html file
{% extends "base.html" %}
{% block content %}
<article class="media content-section">
<div class="media-body">
<div class="article-metadata">
</div>
<div class="row">
<form method="POST" action="/StatsPage">
<select class="btn btn-secondary dropdown-toggle" style="background-color: #FFFFFF; color: #105583;" name="selectedTimeline">
<option style="color: #105583;" disabled selected value= "">Select the option</option>
{% for t in timeline %}
<option style="color: #105583;" value= "{{t}}" SELECTED>{{t}}</option>"
{% endfor %}
</select>
<select class="btn btn-secondary dropdown-toggle" style="background-color: #FFFFFF; color: #105583;" name="selectedDate">
{% for d in dates_dict %}
<option style="color: #105583;" value= "{{d}}" SELECTED>{{d}}</option>"
{% endfor %}
</select>
<button type="submit" name="" class="btn btn-outline-primary">Generate Results</button>
</form>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous">
</script>
<script>
$('select[name=selectedTimeline]').change(function() {
timing = this.value
$.get('/DailyStats/'+timing, function(data, status){
$('select[name=selectedDate]').html('')
data.forEach(function(date){
$('select[name=selectedDate]').append('<option>'+date+'</option>')
})
})
})
</script>
</div>
</article>
{% endblock content %}
All I want to do is
When the user selects the option Daily, the elements in the days_dict list should be displayed, when the user selects the option Weekly, the elements in the week list should be displayed and when the user selects the option Monthly the elements in the months list should be displayed.
I referred to this question on SO, for retrieving the option selected from the first dropdown using AJAX but it didn't help me
So please can someone help me to get this working
Result after answer1
You have to change the syntax in your flask URL. Also you can use AJAX
#app.route('/StatsPage/<timing>', methods=['GET','POST'])
def get_timeline(timing):
Include Jquery CDN.
<article class="media content-section">
<div class="media-body">
<div class="article-metadata">
</div>
<div class="row">
<form method="POST" action="/StatsPage">
<select class="btn btn-secondary dropdown-toggle" style="background-color: #FFFFFF; color: #105583;" name="selectedTimeline">
<option style="color: #105583;" disabled selected value= "">Select the option</option>
{% for t in timeline %}
<option style="color: #105583;" value= "{{t}}">{{t}}</option>
{% endfor %}
</select>
<select class="btn btn-secondary dropdown-toggle" style="background-color: #FFFFFF; color: #105583;" name="selectedDate">
{% for d in dates_dict %}
<option style="color: #105583;" value= "{{d}}">{{d}}</option>
{% endfor %}
</select>
<button type="submit" name="" class="btn btn-outline-primary">Generate Results</button>
</form>
</div>
</div>
</article>
<script>
$('select[name=selectedTimeline]').change(function() {
timing = this.value
$.get('/DailyStats/'+timing, function(data, status){
$('select[name=selectedDate]').html('')
data.forEach(function(date){
$('select[name=selectedDate]').append('<option>'+date+'</option>')
})
})
})
</script>

Get pk_id using function based view

I'm having a problem in getting the pk in my template. When I select a record it always returns the last pk ID. Btw, I'am using functional base view. Here's my collection.html:
<form method="POST" action="{% url 'single_collection' %}">
{% csrf_token %}
<table class="table" id="dataTables-example">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Status</th>
<th>Download</th>
</tr>
</thead>
<tbody>
{% for collectionlist in collection %}
<tr>
<td>{{ collectionlist.id }}</td>
<td>{{ collectionlist.sqa_name }}</td>
<td>{{ collectionlist.status }}</td>
<td class="center"><center><button type="button" class="btn btn-link" data-toggle="modal" data-target="#myModaldl{{ collectionlist.id }}" ><span class="glyphicon glyphicon-download-alt"></span></button></center></td>
</tr>
<div class="modal fade collectClass" id="myModaldl{{ collectionlist.id }}" role="dialog" tabindex="-1">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3 class="modal-title">Single Collect</h3>
</div>
<div class="modal-body form-horizontal">
<div class="form-group">
<label for="inputSQAID" class="col-sm-3 control-label">SQA Name</label>
<div class="col-sm-8">
<input type="hidden" name="pk_id" id="pk_id" value="{{ collectionlist.id }}">
<input type="text" class="form-control" name="singlecollect" value="{{ collectionlist.sqa_name }}" id="inputSQAID">
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-warning" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-success" name="single_dl">Download</button>
</div>
</div>
</div>
</div>
{% endfor %}
</tbody>
</table>
</form>
Here's my views.py:
def collection(request):
context = {
'collection': DataCollection.objects.all(),
'title': 'Data Collection',
}
return render(request, 'data_collection/collection.html', context)
def single_collect(request):
if request.method == 'POST':
pkid = request.POST.get('pk_id')
print(pkid)
all_data = DataCollection.objects.all()
return render(request, 'data_collection/collection.html', {'title' : 'Data Collection', 'data': all_data})
In my views.py, I just want first to print the pk ID of the item/record I selected in my table using the modal. But, it's always getting the last record in my database.
This is because you have a single <form> tag with all the DataCollection rows inside. You should have individual forms for each one, i.e.:
{% for collectionlist in collection %}
<form method="POST" action="{% url 'single_collection' %}">
{% csrf_token %}
...
</form>
{% endfor %}

Passing Parameters From a Class Based View in Django

I have a class based Update view "ManifestUpdate", which is a modal pop up, and is launched from within another function based view "Manifest". I need to be able to take the field = 'reference' from my ManifestUpdate view and make it available to the "Manifest" view as 'Reference_Nos'. As you can see ManifestUpdate should direct the user to Manifest, but it does not, just nothing happens (it works if I change this to direct to any other view). I believe this is because I am not passing that parameter. Can anyone tell me how to capture that 'reference' parameter within ManifestUpdate and pass it to Manifest from the class based view?
views.py
class ManifestUpdate(BSModalUpdateView):
model = Manifests
template_name = 'manifest_update.html'
form_class = UpdateManifestForm
success_message = 'Success: Manifest was updated.'
success_url = reverse_lazy('manifest')
def manifest(request):
form = CreateManifestForm(request.POST)
if request.method == "POST":
if form.is_valid():
form.save()
reference_id = form.cleaned_data.get('reference')
data = Manifests.objects.all().filter(reference__reference=reference_id)
form = CreateManifestForm(initial={
'reference': Orders.objects.get(reference=reference_id),
})
total_cases = Manifests.objects.filter(reference__reference=reference_id).aggregate(Sum('cases'))
context = {
'reference_id': reference_id,
'form': form,
'data': data,
'total_cases': total_cases['cases__sum'],
}
return render(request, 'manifest_readonly.html', context)
else:
reference_id = request.POST.get('Reference_Nos')
data = Manifests.objects.all().filter(reference__reference=reference_id)
form = CreateManifestForm(initial={
'reference': Orders.objects.get(reference=reference_id),
})
total_cases = Manifests.objects.filter(reference__reference=reference_id).aggregate(Sum('cases'))
context = {
'reference_id': reference_id,
'form': form,
'data': data,
'total_cases': total_cases['cases__sum'],
}
return render(request, 'manifest_readonly.html', context)
forms.py
class UpdateManifestForm(BSModalForm):
class Meta:
model = Manifests
fields = ('reference', 'cases', 'product_name', 'count', 'CNF', 'FOB')
update_manifest.html
#showing the modal window body
<form method="post" action="">
{% csrf_token %}
<div class="modal-header">
<h3 class="modal-title">Update Manifest</h3>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="{% if form.non_field_errors %}invalid{% endif %} mb-2">
{% for error in form.non_field_errors %}
{{ error }}
{% endfor %}
</div>
<div class="container">
<form id="create_mani_form" method="POST">
<br>
{% csrf_token %}
<div class="column">
<label for="form.reference" class="formlabels">Reference ID: </label><br>
<!-- <input type="text" value="{{ reference_id }}">-->
{{ form.reference }}
<br>
<br>
<label for="form.count" class="formlabels">CNF: </label>
<br>
{{ form.CNF }}
<br>
</div>
<div class="description">
<div class="column">
<label for="form.product_name" class="formlabels">Description: </label>
<br>
{{ form.product_name}}
<br><br>
<label for="form.count" class="formlabels">FOB: </label>
<br>
{{ form.FOB }}
<br>
</div>
</div>
<div class="column">
<label for="form.cases" class="formlabels">Cases: </label>
<br>
{{ form.cases }}
<br>
</div>
<div class="column">
<label for="form.count" class="formlabels">Count: </label>
<br>
{{ form.count }}
<br>
</div>
</div>
<div class="modal-footer">
<button type="button" class="submit-btn btn btn-primary">Update</button>
</div>
</form>
manifest_readonly.html
#showing the html rendered by the manifest view
{% extends 'base.html' %}
{% load humanize %}
{% block body %}
{% load staticfiles %}
<div class="container">
<div class="col-xs-12">
{% if messages %}
{% for message in messages %}
<div class="alert alert-success" role="alert">
<center>{{ message }}</center>
</div>
{% endfor %}
{% endif %}
</div>
</div>
<div class="container">
<form id="create_mani_form" method="POST">
<br>
<br>
<br>
{% csrf_token %}
<div class="column">
<label for="form.reference" class="formlabels">Reference ID: </label><br>
<!-- <input type="text" value="{{ reference_id }}">-->
{{ form.reference }}
<br>
<br>
<label for="form.count" class="formlabels">CNF: </label>
<br>
{{ form.CNF }}
<br>
</div>
<div class="description">
<div class="column">
<label for="form.description" class="formlabels">Description: </label>
<br>
{{ form.product_name}}
<br><br>
<label for="form.count" class="formlabels">FOB: </label>
<br>
{{ form.FOB }}
<br>
</div>
</div>
<div class="column">
<label for="form.cases" class="formlabels">Cases: </label>
<br>
{{ form.cases }}
<br>
</div>
<div class="column">
<label for="form.count" class="formlabels">Count: </label>
<br>
{{ form.count }}
<br>
<label for="form.reference" class="formlabels">Case Total: </label><br>
<input type="text" value="{{ total_cases|intcomma }}" readonly>
<br>
<label for="form.reference" class="formlabels">Total CNF: </label><br>
<input type="text" value="{{ totalCNF|intcomma }}" readonly>
<br>
<label for="form.reference" class="formlabels">Total FOB: </label><br>
<input type="text" value="{{ totalFOB|intcomma }}" readonly>
</div>
<br>
<br>
<button type="submit" name="add_mani" style="border-color: #7395AE;">Add Line</button>
</form>
<br>
<h4>Manifest</h4>
<div class="table-responsive">
<!--<table id="manifest_table" class="table table-striped table-bordered table-sm " cellspacing="0"-->
<table class="table table-striped table-bordered manifest_table" cellspacing="0" style="width="100%">
<thead>
<tr>
<th style="width:2%;"</th>
<th style="width:10%;">Cases</th>
<th style="width:60%;">Description</th>
<th style="width:10%;">Count</th>
<th style="width:10%">FOB</th>
<th style="width:10%">CNF</th>
</tr>
</thead>
<tbody>
{% for manifests in data %}
<tr>
<td>
<!-- Update book buttons -->
<button type="button" class="update-manifest btn btn-sm btn-primary" style="color: #FFCF8B; border-color: #FFCF8B; background-color: #FFF;" data-id="{% url 'manifest_update' manifests.pk %}">
<span class="fa fa-pencil"></span>
</button>
</td>
<td>{{ manifests.cases }}</td>
<td>{{ manifests.product_name}}</td>
<td>{{ manifests.count}}</td>
<td>{{ manifests.FOB}}</td>
<td>{{ manifests.CNF}}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<div class="text-center">
Subit Manifest
</div>
<div class="modal fade" tabindex="-1" role="dialog" id="modal">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content"></div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/dataTables.bootstrap4.min.js"></script>
<script src="jquery.min.js"></script>
<script src="jquery.fulltable.js"></script>
<script src="script.js"></script>
<script src="{% static 'js/jquery.bootstrap.modal.forms.js' %}"></script>
<script>
$(function () {
$(".update-manifest").each(function () {
$(this).modalForm({formURL: $(this).data('id')});
});
});
</script>
{% endblock %}
jquery.bootstrap.modal.forms.js
(function ($) {
// Place the form at formURL to modalContent element of modal with id=modalID
var newForm = function (modalID, modalContent, modalForm, formURL, successURL, errorClass) {
$(modalContent).load(formURL, function () {
$(modalID).modal('toggle');
ajaxSubmit(modalID, modalContent, modalForm, successURL, errorClass);
});
};
// Add AJAX validation to the modalForm
var ajaxSubmit = function (modalID, modalContent, modalForm, successURL, errorClass) {
$(modalForm).submit(function (event) {
// Prevent submit and POST form to url using AJAX
event.preventDefault();
$.ajax({
type: $(this).attr("method"),
url: $(this).attr("action"),
// Serialize form data
data: $(this).serialize(),
success: function (response) {
// Update form with errors after unsuccessful POST request
// Django form.is_valid() = False
if ($(response).find(errorClass).length > 0) {
$(modalID).find(modalContent).html(response);
ajaxSubmit(modalID, modalContent, modalForm, successURL, errorClass);
}
// Hide modal after successful POST request when & redirect to successURL
else {
$(modalID).modal("hide");
window.location.href = successURL;
}
}
});
});
};
$.fn.modalForm = function (options) {
// Default settings
var defaults = {
modalID: "#modal",
modalContent: ".modal-content",
modalForm: ".modal-content form",
formURL: null,
successURL: "/",
errorClass: ".invalid"
};
// Extend default settings with provided options
var settings = $.extend(defaults, options);
return this.each(function () {
$(this).click(function (event) {
newForm(settings.modalID,
settings.modalContent,
settings.modalForm,
settings.formURL,
settings.successURL,
settings.errorClass);
event.preventDefault();
});
});
};
}(jQuery));

how to display google map in between the dashboard

while running flask server throwing this error Uncaught TypeError: Cannot read property 'firstChild' of null at Object._.Og (js?key=AIzaSyAbZKo3h1LVhyoURgxcSUG9BGVvZtZpg0U:88) at new Sg (js?key=AIzaSyAbZKo3h1LVhyoURgxcSUG9BGVvZtZpg0U:89)
I'm new google maps in Python-Flask.google map is not showing while running the Flask localhost server.but,it showing while running the template.i'm not aware where i have mistaken in my source code. I need only show the map in between the empty place. here is the dashboard where place be the map here
yesterday i posted answer that is working.but it's showing like Uncaught TypeError: Cannot read property 'firstChild' of null at Object._.Og (js?key=AIzaSyAbZKo3h1LVhyoURgxcSUG9BGVvZtZpg0U:88) at new Sg (js?key=AIzaSyAbZKo3h1LVhyoURgxcSUG9BGVvZtZpg0U:89) where is the problem
Here is the google map code:
{% extends "base.html" %}
{% block head %}
{{super()}}
{% endblock %}
{% block navbar %}
{{super()}}
{% endblock %}
{% block content %}
<div class="row">
<ol class="breadcrumb">
<li><a href="#">
<em class="fa fa-home"></em>
</a></li>
<li class="active">Locations>create locations</li>
</ol>
</div><!--/.row-->
<div class="row">
<div class="col-md-6">
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=AIzaSyDv8X0eEAWUtWZrHG_1XLB8gMNxgdcD0-U"></script>
<script >
window.onload = function () {
var mapOptions = {
center: new google.maps.LatLng(17.3850, 78.4867),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var infoWindow = new google.maps.InfoWindow()
var name;
var lat;
var lng;
var latlngbounds = new google.maps.LatLngBounds();
var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);
google.maps.event.addListener(map, 'click', function (e) {
var latlng = new google.maps.LatLng(e.latLng.lat(), e.latLng.lng());
var geocoder = geocoder = new google.maps.Geocoder();
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: 'Hello World!'
});
geocoder.geocode({ 'latLng': latlng }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
name= results[1].formatted_address;
lat=e.latLng.lat();
lng=e.latLng.lng();
alert("Location: " +name + "\r\nLatitude: " + lat + "\r\nLongitude: " +lng );
document.getElementById("loc").value=name;
document.getElementById("lat").value=lat;
document.getElementById("lng").value=lng;
}
}
});
});
}
</script>
<!--<div id="dvMap" style="width: 50%; height: 50%">-->
<!--</div>-->
<form role="form" action="/post/locations" method="post" >
<input type="text" id="loc" name="name" class="form-control"/>
<input type="text" name="latitude" id="lat" class="form-control"/>
<input name="longitude" id="lng" type="text" class="form-control"/>
<input type="submit" class="btn btn-primary" value="Submit">
<input type="reset" class="btn btn-default" value="Reset">
</form>
</div>
</div>
<div id="dvMap" style="width: 80%; height: 70% ">
</div>
{% endblock %}
Here is the Python code:
#app.route('/page/locations')
def location():
if session['username']:
return render_template('map.html',user=session['username'])
else:
print ('login first!')
return redirect('/dashboard')
I just found the answer.Here it is my answer.
{% extends "base.html" %}
{% block head %}
{{super()}}
{% endblock %}
{% block navbar %}
{{super()}}
{% endblock %}
{% block content %}
<div class="row">
<ol class="breadcrumb">
<li><a href="#">
<em class="fa fa-home"></em>
</a></li>
<li class="active">Locations>Create Locations</li>
</ol>
</div><!--/.row id="entry.id" id="uploadbanner"-->
<div id="dvMap" style="width: 100%; height: 100%">
</div>
<form role="form" action="/post/locations" method="post">
<label>Name:</label>
<input type="text" id="loc" name="name"/>
<label>Latitude:</label>
<input type="text" name="latitude" id="lat"/>
<label>Longitude:</label>
<input name="longitude" id="lng" type="text"/>
<input type="submit" class="btn btn-primary" value=" Submit ">
<input type="reset" class="btn btn-default" value="Reset">
</form>
{% endblock %}
I just add the script in Javascript folder .
as a like <--static/assets/js/map.js --> in my template base.html source code.
The problem with your code is the javascript snippet is getting executed before the div element ( one with id="dvMap" ) is created. So either place the javascript snippet after the div element like below,
{% extends "base.html" %}
{% block head %}
{{super()}}
{% endblock %}
{% block navbar %}
{{super()}}
{% endblock %}
{% block content %}
<div class="row">
<ol class="breadcrumb">
<li><a href="#">
<em class="fa fa-home"></em>
</a></li>
<li class="active">Locations>create locations</li>
</ol>
</div>{# /.row #}
<div class="row">
<div class="col-md-6">
{# <div id="dvMap" style="width: 50%; height: 50%"></div> #}
<form role="form" action="/post/locations" method="post" >
<input type="text" id="loc" name="name" class="form-control"/>
<input type="text" name="latitude" id="lat" class="form-control"/>
<input name="longitude" id="lng" type="text" class="form-control"/>
<input type="submit" class="btn btn-primary" value="Submit">
<input type="reset" class="btn btn-default" value="Reset">
</form>
</div>
</div>
<div id="dvMap" style="width: 80%; height: 70% ">
</div>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=AIzaSyDv8X0eEAWUtWZrHG_1XLB8gMNxgdcD0-U"></script>
<script >
window.onload = function () {
var mapOptions = {
center: new google.maps.LatLng(17.3850, 78.4867),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var infoWindow = new google.maps.InfoWindow()
var name;
var lat;
var lng;
var latlngbounds = new google.maps.LatLngBounds();
var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);
google.maps.event.addListener(map, 'click', function (e) {
var latlng = new google.maps.LatLng(e.latLng.lat(), e.latLng.lng());
var geocoder = geocoder = new google.maps.Geocoder();
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: 'Hello World!'
});
geocoder.geocode({ 'latLng': latlng }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
name= results[1].formatted_address;
lat=e.latLng.lat();
lng=e.latLng.lng();
alert("Location: " +name + "\r\nLatitude: " + lat + "\r\nLongitude: " +lng );
document.getElementById("loc").value=name;
document.getElementById("lat").value=lat;
document.getElementById("lng").value=lng;
}
}
});
});
}
</script>
{% endblock %}
Or make a separate js file ( here I have named it custom.js for an example ) in the static folder with the javascript code in it and add <script src='{{ url_for('static', filename='custom.js') }}'></script> at the end of the file.
I hope this helps you.
PS :- Please use the jinja2 comment tags while commenting in jinja2 template file. You can refer it here.

Styling an Accordion Table

I made this accordion table using bootstrap accordion. It works well, but it looks terrible. The way I have it set up is a nested accordion. the code can be seen as follows:
<!DOCTYPE html>
<html>
<head>
{% load staticfiles %}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<!-- {# Load CSS and JavaScript #} -->
<!-- {# Load the tag library #} -->
{% load bootstrap3 %}
{% bootstrap_css %}
{% bootstrap_javascript %}
{% block javascript %}
<script>
//this is not working as yet
$(document).ready(function() {
//script to refresh div - formclass is class name of form
$('#formclass2').submit(function(event){
var servername = $('#servername').val();
var divname=servername+"div";
$.ajax({
url: 'formsubmitcode',
type: 'post',
dataType:'html', //expect return data as html from server
data: $('#formclass').serialize(),
success: function(response, textStatus, jqXHR){
$('#'+divname).html(response); //select the id and put the response in the html
},
error: function(jqXHR, textStatus, errorThrown){
console.log('error(s):'+textStatus, errorThrown);
}
});
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
var frm = $('#myform');
frm.submit(function () {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'), //picks up the action from form
data: frm.serialize(),
success: function (data) {
$("#test").html(data);
$("MESSAGE-DIV").html("Something not working");
},
error: function(data) {
$("#MESSAGE-DIV").html("Something went wrong!");
}
});
ev.preventDefault();
});
});
</script>
{% endblock %}
</head>
<body>
<ul>
{% for checkkey,checkvalue in orgnizedDicts.items %}
<div class="accordion text-left" id="accordion1">
<div class="accordion-group">
<div class="accordion-heading">
<a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion1{{checkkey}}" href="#collapseOne{{checkkey}}">
{{checkkey}}
</a>
</div>
<div id="collapseOne{{checkkey}}" class="accordion-body collapse">
<div class="accordion-inner">
<!-- Here we insert another nested accordion -->
{% for servkey,servvalue in checkvalue.items %}
<div class="accordion" id="accordion2{{servkey}}">
<div class="accordion-group">
<div class="accordion-heading">
<a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion2{{servkey}}" href="#collapseInnerOne{{servkey}}">
{{servkey}}
</a>
</div>
<div id="collapseInnerOne{{servkey}}" class="accordion-body collapse">
<div class="accordion-inner">
<!-- table row header -->
<table class="table table-bordered table-striped">
<tr>
<th>Servicename</th>
<th>Curent status</th>
<th>Action</th>
</tr>
{% for servicekey,servicevalue in servvalue.items %}
<tr>
<td><input type="hidden" name="servername" value="{{servkey}}">
<input type="text" name="servicename" value="{{servicekey}}"></td>
<td>{{servicevalue}}</td><!--status-->
<td><input type="submit" value="Start" name="Start">
<input type="submit" value="Stop" name="Stop">
<input type="submit" value="Restart" name="Restart"</td>
<!-- </form> -->
<!-- </div> -->
<div id="MESSAGE-DIV"></div>
</tr>
{% endfor %}
</table>
</div>
</div>
</div>
</div>
<!-- Inner accordion ends here -->
{% endfor %}
</div>
</div>
</div>
</div>
{% endfor %}
</body>
</html>
It's part of a django project so I'm using their templating language to bring in the data to populate the table and generating it dynamically. the data that I'm calling in is a nested dict nested within another dict. My table actually starts within the second nested accordion though. On the nested collapsible part of the accordion I want to do some formatting but I'm a rookie with html and css and I just want to give the outter accordion a border and make it black with white text, and give the inner accordion a border and change make thm green. I also should probably change the buttons to bootstrap buttons but I think that's pretty easy.

Categories

Resources