Styling an Accordion Table - python

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.

Related

Unable to get through .is_valid() validation of Django for POST request for Images field

The POST request for images does not get validated on my form, when i created a new form it worked fine and was able to save the images. but going back to same old form i tried making the body part similar to the old one but got the same message even tried to check the console for form.errors but couldn't find anything.Still trying to figure out what is it that's missing in input as per the console log ValidationError[This field is required].
console log for the POST Request made
View.py function used to validate and get post
models.py
form.py ModelForm
main layout html template
<!DOCTYPE html>
<html lang="en">
<head>
<!-- <title>Encyclopedia</title> -->
<title>{% block title %} {% endblock %}</title>
<link rel="stylesheet" href="..\..\static\mywikiapp\style.css">
{% block head %}
{% endblock %}
</head>
<body>
<div class="main">
<div class="leftpart">
<h2 id="leftheading">Wiki</h2>
<div class="search_container_confinement">
<form>
<div class="searchcontainer">
<input type="text" name="q" placeholder="Search Encyclopedia">
</div>
</form>
</div>
<div class="listcontainer">
<ul id="left_col_li">
<li>Home</li>
<li>Create New Page</li>
<li>Upload Images</li>
<li>Random Page</li>
</ul>
</div>
<div class="navbar">
<div>
{% block navbar %}{% endblock %}
</div>
</div>
</div>
<div class="rightpart">
<!-- <h1>All Pages</h1>
<div>
<ul>
<li>Css</li>
<li>Django</li>
<li>Git</li>
<li>HTML</li>
<li>Python</li>
</ul>
</div> -->
{% block body %}{% endblock %}
</div>
</div>
</body>
</html>
The Template in which validation fails.The variable formimg is the modelform for imagefield passed rendered to the html to select mutiple images
{% extends "mywikiapp/layout.html" %}
{% block title %}
Add Images
{% endblock %}
{% block head %}
<style>
.rightpart{
/* border:black solid; */
display:grid;
place-items: center;
}
</style>
{% endblock head %}
{% block body %}
<div class="btn">
<form class="add_images" enctype="mutipart/form-data" name="Upload_Images" action="{% url 'mywikiapp:save_image' %}" method="POST">
<!-- <form class="add_images" enctype="multipart/form-data" name="Upload_Images" action="{% url 'mywikiapp:save_image' %}" method="POST"> -->
<div>
<input type="submit" value="Save Images">
{% csrf_token %}
{{formimg.management_form}}
{% for i in formimg %}
{{i}}
{% endfor %}
</div>
<!-- {{formimg}} -->
<!-- <input required name="images" type="file" multiple="multiple" name="images"> -->
</form>
</div>
{% endblock %}
The html form in which validation works without any errors.
<!DOCTYPE html>
<html>
<head>
<title>Upload images</title>
<style>
body {
height:100vh;
width:100vh;
}
.rightpart{
/* border:black solid; */
display:grid;
place-items: center;
height:100%;
width:100%;
}
</style>
</head>
<body>
<div class="rightpart">
<div class="btn">
<form class="add_images" enctype="multipart/form-data" name="Upload_Images" action="{% url 'mywikiapp:save_image' %}" method="POST">
<div>
<input type="submit" value="Save Images">
{% csrf_token %}
{{formimg.management_form}}
{% for i in formimg %}
{{i}}
{% endfor %}
</div>
<!-- {{formimg}} -->
<!-- <input required name="images" type="file" multiple="multiple" name="images"> -->
</form>
</div>
</div>
</body>
</html>

Why can't I see Loading... while scrolling?

Based on this tutorial
This is my views:
def All( request ):
p=product.objects.all().order_by('id')
pa=Paginator(p,20)
page=request.GET.get('page')
pro=pa.get_page(page)
return render(request,'home.html',{'pro':pro})
This is my template:
<div class="grid">
{%for p in pro%}
<div class='card'>
<img src="{{p.image}}"></img>
<p id="id">{{p.description}}</p>
<a href="{{p.buy}}" target='_blank' rel='noopener noreferrer'>
<button ><span class="price"> ${{p.price}}</span> buy</button>
</a>
</div>
{%endfor%}
{% if pro.has_next %}
<a class='more-link' href="?page={{pro.next_page_number}}">Next</a>
{% endif %}
<div class="loading" style="display: none;">
Loading...
</div>
<script>
var infinite = new Waypoint.Infinite({
element: $('.grid')[0],
onBeforePageLoad: function () {
$('.loading').show();
},
onAfterPageLoad: function ($items) {
$('.loading').hide();
}
});
</script>
</div>
I have downloaded dependencies correctly and I included some links in my html to use them, but currently I'm not able to find what is wrong with my code.
server response
Why can't I see Loading... while scrolling?

Django pop up modal after Inserting/updating data

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

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.

Categories

Resources