Am using Django in my project. I have a resources.py(JSON file) which consists of all my required data from the database.
I have an html file which consists of several dropdown buttons, my aim is to once I select one dropdown option it will pass that value and get values for successive dropdown button dynamically.
My HTML:
<div class="wall" ng-controller="LayerCtrl" >
<table>
<tr>
<td>
<div class="input-group">
<span class="input-group-addon">Fab</span>
<select class="form-control" name="fab">
{% for f in fab %}
<option value="{{f}}">{{f}}</option>
{% endfor %}
</select>
</div>
</td>
<td>
<div class="input-group">
<span class="input-group-addon">Technode</span>
<select class="form-control" ng-model="selected_technode" ng-options="l.value as l.label for l in technodes"></select>
</div>
</td>
<td>
<div class="input-group">
<span class="input-group-addon">Layer</span>
<!--<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">-->
{%verbatim%}
<!--<select class="form-control" name="layer" >-->
<!--<option ng-repeat="l in layer_list" value="{{l}}">{{l}}</option>-->
<!--</select>-->
<select class="form-control" ng-model="selected_layer" ng-options="l as l for l in layerlist"></select>
{%endverbatim%}
</div>
</td>
</tr>
</table>
</div>
and my JS:
{{ ngapp }}.controller("LayerCtrl", function ($scope, $http, $resource){
var layerresource_url = $resource("{% url 'api_dispatch_list' 'v1' 'layer' %}");
$scope.technodes = [
{'value': 22, 'label': 22},
{'value': 28, 'label': 28},
];
console.log('initializing....')
$scope.$watch('selected_technode', function () {
<!--alert($scope.selected_technode);-->
$scope.update_layer();
});
$scope.update_layer = function(){;
console.log('Stage1: Initializing Primary Data... ');
layerresource_url.get({techtype__contains: $scope.selected_technode, limit:1500},
function(data){
$scope.layerlist = data['objects'][0]['layer'];
console.log($scope.layerlist);
},function(data, status){
console.log('Stage1: Internal error while loading initial data:'+status );
alert('internal error');
}
);
};
});
I need to pass the value get from the technode dropdown button and display the respective results in lalyer dropdown box. How can I do that? Thanks in advance.
EDITTED
Now I hardcoded the options in JS file. But I need to replace this options in python way (Like I did to get the fab). How to do that?
The usage for select fields is:
<select
ng-model="string"
[name="string"]
[required="string"]
[ng-required="string"]
[ng-change="string"]
[ng-options="string"]>
...
</select>
Here is the documentation: https://docs.angularjs.org/api/ng/directive/select
<select class="form-control" ng-model="selected_technode" name="technode">
{% for t in technode %}
<option value="{{f}}">{{t}}</option>
{% endfor %}
</select>
In your controller you can watch for changes and trigger an ajax call:
$scope.$watch('selected_technode', function (newVal) {
updateLayer(newVal);
});
function updateLayer(technode) {
var m = $resource(layerresource_url);
var data = m.get({format: json, techtype__contains: technode});
$scope.layer = data.objects[0];
}
Related
Html
<!DOCTYPE html>
<html>
<div class="wrapper">
{%if messages %}
{% for message in messages %}
<div class="alert {{ message.tags }} alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
{{ message }}
</div>
{% endfor %}
{% endif %}
<div class="register-page">
<div class="register-container">
<form id="appointment-form" role="form" method="post" enctype='multipart/form-data'>
<!-- SECTION TITLE -->
<div class="section-title wow fadeInUp" data-wow-delay="0.4s">
<h2>Book Appointment</h2>
</div>
{% csrf_token %}
<input name="patient_name" value="{{request.user}}" hidden>
<div class="wow fadeInUp" data-wow-delay="0.8s">
<div class="col-md-6 col-sm-6">
<label for="name">Clinic name</label>
{{ form.clinic_name }}
</div>
<div class="col-md-6 col-sm-6">
<label for="qualification">Doctor Name</label>
{{ form.doctor_name }}
</div>
<!-- try -->
<p id="p-text">foo bar</p>
<div class="col-md-6 col-sm-6">
<label for="specialist"> Date</label>
{{ form.date }}
</div>
<!-- try -->
<p id="d-text">foo bar</p>
<div class="col-md-6 col-sm-6">
<label for="location">Time slot </label>
<!-- {{ form.time_slot }} -->
<select name="time_slot" required="" id="id_time_slot">
<option value="" selected="">---------</option>
<option value="09:00 - 10:00" id="op0">09:00 - 10:00</option>
<option value="10:00 - 11:00" id="op1">10:00 - 11:00</option>
<option value="11:00 - 12:00" id="op2">11:00 - 12:00</option>
<option value="12:00 - 13:00" id="op3">12:00 - 13:00</option>
<option value="13:00 - 14:00" id="op4">13:00 - 14:00</option>
<option value="14:00 - 15:00" id="op5">14:00 - 15:00</option>
<option value="15:00 - 16:00" id="op6">15:00 - 16:00</option>
<option value="16:00 - 17:00" id="op7">16:00 - 17:00</option>
<option value="17:00 - 18:00" id="op8">17:00 - 18:00</option>
</select>
</div>
<div class="col-md-12 col-sm-12">
<label for="description"> Description</label>
{{ form.description }}
<br>
<button type="submit" class="submitButton" id="cf-submit" name="submit">Submit Button</button>
</div>
</div>
</form>
</div>
</div>
</div>
<script>
// Date
$("#txtDate").change(function () {
var input = $(this).val()
$("#id_time_slot").attr("disabled", false);
$.ajax({
url: "{% url 'get_timeslot' %}",
data: {
'inputDate': input
},
dataType: 'json',
success: function (data) {
var myOpts = document.getElementById('id_time_slot').options;
data.forEach(function(entry)
{
var a = document.getElementById('op'+entry).disabled = true;
console.log(a);
});
}
});
});
</script>
</html>
{% endblock %}
I have tried every thing as shown, Before Ajax call I am setting All elements as Disabled=false;
then too when I call ajax it is working and set disabled=true. But For next time When I change Date, It will show same dates disabled from first only. As I change the date , I want all element to be Disabled=false, then go in success to disabled perticural timeslots.
I solved this ,by simply replacing the line
$("#id_time_slot").attr("disabled", false);
With this line before calling Ajax
$("#id_time_slot option").prop('disabled', false);
This is a solution that involves using pure javascript with cleaner code without mixing things up:
let data = [0, 1, 2, 3, 4, 5, 6, 7, 8]; //fake data for snippet
const input = document.querySelector('#txtDate');
const select = document.querySelector('#id_time_slot');
input.addEventListener('change', (e) => {
input.disabled = true; //disabled until ajax work
const value = input.value;
select.querySelectorAll('option').forEach(el => {
el.disabled = false; //re-enable all options
});
setTimeout(() => { //fake ajax for snippet
data.forEach(el => {
document.querySelector('#op' + el).disabled = true; //disabled fake result of data ajax
});
data.shift(); // just for change result
input.disabled = false; // enabled input again
}, 5000);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="txtDate">
<br>
<select name="time_slot" required="" id="id_time_slot">
<option value="" selected="">---------</option>
<option value="09:00 - 10:00" id="op0">09:00 - 10:00</option>
<option value="10:00 - 11:00" id="op1">10:00 - 11:00</option>
<option value="11:00 - 12:00" id="op2">11:00 - 12:00</option>
<option value="12:00 - 13:00" id="op3">12:00 - 13:00</option>
<option value="13:00 - 14:00" id="op4">13:00 - 14:00</option>
<option value="14:00 - 15:00" id="op5">14:00 - 15:00</option>
<option value="15:00 - 16:00" id="op6">15:00 - 16:00</option>
<option value="16:00 - 17:00" id="op7">16:00 - 17:00</option>
<option value="17:00 - 18:00" id="op8">17:00 - 18:00</option>
</select>
I simulated an ajax with a "setTimeOut" every 5 seconds the fake function will change the select
How should I extract data from a database using ajax in Django and display it in view in the form of charts. I wanna select items from dropdown options and then display those selected data in the webpage in the form of charts.
Can anyone please guide me in this.
My codes are:
index.html:
<div class="row">
<form class="form-row" action="{{ }}" method="post">
{% csrf_token %}
<div class="form-group col-md-2">
<select class="form-control select2" >
<option>Select Major Head</option>
{% for major in majors %}
<option value="{{ major.pk }}">{{ major.pk }}: {{ major.description } </option>
{% endfor %}
</select>
</div>
<div class="form-group col-md-2">
<input type="submit" value="Display">
</div>
</form>
</div>
.
.
.
<div class="card-body" >
<div id="chart">
<embed type="image/svg+xml" src= {{ chart|safe }} />
</div>
views.py:
def home(request):
majors = Major.objects.filter(percentages__isnull=False).distinct().order_by("pk")
if request.method == 'POST':
form = request.POST.get('be_nextyr_total')
line_chart = pygal.Line(width=1500)
line_chart.title = 'Budget Estimation'
context = {
"chart": line_chart.render_data_uri(),
'majors': majors
}
return render(request, "website/index.html" , context )
charts.js
$('form').on('Display',function(e){
e.preventDefault();
$.ajax({
type : "POST",
cache : false,
url : $(this).attr('action'),
data : $(this).serialize(),
success : function(data) {
// $(".printArea").empty().append(data).css('visibility','visible');
return data;
}
});
});
So I am creating a table with a form and I have 2 rows the problem is the submit button works only on one button and the second submit it does the form but doesn't send any values
<tr>
{% for(username, computer_mac, assign_value) in zip(users_username, computers_mac, assigned_values) %}
<form action="" method="POST">
<td>
computer number:
<select class="custom-select" name={{username}}>
{% for client_id in computer_client_id%}
<option value={{client_id}} name={{client_id}} >{{client_id}}</option>
{% endfor %}
<option value="-1" name="-1">None</option>
<option hidden selected>{{assign_value}}</option>
</select>
</td>
<td>{{username}} ({{computer_mac}})</td>
<td class="assigned_values">{{assign_value}}</td>
<td>
<input type="submit" class="btn btn-danger btn-md a" id="button-id" value="submit">
</td>
<td>
<div id="status"></div>
</td>
</form>
</tr>
{% endfor %}
{{username}} = Raz
{{client_id}} = 1
{{other_username}} = a
{{other_client_id}} = None
in the first button, I can see that it "{{username}}={{client_id}}&{{other_username}}={{other_client_id}}" what I'd like to have is for every button it'd be separate so the first button will have his {{username}}={{client_id}} and the second button would have his {{other_username}}={{other_client_id}} how do I do it?
JS data send:
var data = $("form").serialize();
console.log(data);
$.ajax({
type: "POST",
url: 'admin/data',
data: data,
So I solved it the first problem was that I needed to create a class for the button so it will work on multiple buttons instead of 1:
so simply adding to the button class: "button-class" and delete the id
now the problem is that for both of the buttons the form output is this Raz=1&a=None which could be good for you but I wanted them separate so
button 1 - Raz=1
button 2 - a=None
so what I did is that I found the index of the button that I am clicking on
var currentIndex = $('.button-class').index(this);
and simply split at &
try{
data = data.split('&');
data = data[currentIndex]
}
catch(err){
data = ""
}
and that's it now I have the right info for the different buttons.
I've been working on a Django form. The form is in the poc_add.html site. The index.html side contains the
<div id="output"></div>
that is being filled out with the poc_add.html content. In other words the poc_add.html site is a part of the index.html site.
Here is the code of the form:
<form class="form">
{% csrf_token %}
<fieldset>
<label class="mb-0" for="cmbLocation">Location</label>
<div style="padding-bottom: 15px;" class="row mb-1">
<div class="col-lg-12">
<select class="form-control" id="cmbLocation">
{% for location in locations %}
<option value="{{ location.0 }}">{{ location.1 }}</option>
{% endfor %}
</select>
</div>
</div>
<label class="mb-0" for="cmbCertification">Certification</label>
<div style="padding-bottom: 15px;" class="row mb-1">
<div class="col-lg-12">
<select class="form-control" id="cmbCertification">
<option>Lead Prep</option>
<option>Greeter</option>
<option>Lead Trainer</option>
</select>
</div>
</div>
......
......
<div id="divAddNewPOC" style="padding-bottom: 10px;padding-left: 2px;">
<button class="btn btn-primary custom-btn" id="btnNewPOC" data-dismiss="modal">Save</button>
</div>
</fieldset>
</form>
Here is some JavaScript codes of the poc.js file that is included in the poc_add.html page.
$("#btnNewPOC").click(function(){
var selectedLocationVal = $("#cmbLocation").val();
var selectedCertificationVal = $("#cmbCertification").val();
console.log("Location val: " + selectedLocationVal);
console.log("Current Objective val: " + selectedCurrentObjVal);
console.log("Correct Uniform val: " + selectedCorrectUniformVal);
$.post("poc_form_submit",{'location': selectedLocationVal,
'certification': selectedCertificationVal,
......
......
......
},
function(data) {
.....
.....
.....
}, "html");
});
Here is some part of the urls.py file
urlpatterns = [
path('', views.login, name='login'),
path('index', views.index, name='index'),
....
....
....
path('poc_form_submit', views.poc_form_submit, name='poc_form_submit'),
]
When I click the submit button, it refreshes the index.html site. What I need is to refresh only the poc_add.html page. How can I accomplish that?
Your view must return rendered poc_add.html
and than:
$("#btnNewPOC").click(function(){
var selectedLocationVal = $("#cmbLocation").val();
var selectedCertificationVal = $("#cmbCertification").val();
console.log("Location val: " + selectedLocationVal);
console.log("Current Objective val: " + selectedCurrentObjVal);
console.log("Correct Uniform val: " + selectedCorrectUniformVal);
$.post("poc_form_submit",
{'location': selectedLocationVal,
'certification': selectedCertificationVal,
......
......
......},
function(data) {
// Rendered poc_add.html from your view
$("#output").html(data);
}
);
});
I want to print certain attribute values in html. For this, I appended those values to a list (List) in views.py, and passed it via context to the corresponding template (viewperformance.html). When I print List in views.py, it gives a list of numbers, as expected. However, record in template prints no value at all.
VIEWS.PY
#csrf_protect
#login_required
def edit_marks(request, course_code):
# Some code irrelevant to the problem has been removed
List = list()
for i in range(len(registered_students)):
m_id = registered_students[i]
s = score[i]
rows = Marks.objects.filter(mid=m_id, exam_type=exam)
num = Marks.objects.filter(mid=m_id, exam_type=exam).count()
record = Marks.objects.filter(mid=m_id, exam_type=exam).values_list('marks', flat=True)
List.append(list(record))
if num==0:
Marks.objects.create(
mid=m_id,
exam_type=exam,
marks=s
)
else:
Marks.objects.filter(mid=m_id, exam_type=exam).update(marks=s)
print(List)
return HttpResponse("Upload successful")
context= {'registered_students': registered_students, 'record':List}
return render(request, 'coursemanagement/viewperformance.html', context)
viewperformance.html
{% load static %} {% block viewperformance %}
<div>
<form class="ui large form" name="entermarks" id="entermarks" method="POST" action="/ocms/{{curriculum.course_code}}/edit_marks">
{% csrf_token %}
<select name="examtype" id = "examtype" style="width: 100px">
<option value = "Quiz 1">Quiz 1</option>
<option value = "Quiz 2">Quiz 2</option>
<option value = "Mid Sem">Mid Sem</option>
<option value = "End Sem">End sem</option>
</select>
<table class="ui very basic collapsing celled table">
<thead>
<tr>
<th>Students</th>
</tr>
</thead>
<tbody>
<p> 'Value of record : ' {{ record }} </p>
{% for x in registered_students %}
<tr>
<td>
<div class="content">
<p style="text-align:center">{{x.student_id}}</p>
</div>
</td>
<td>
<input type="number" name="enteredmarks" id="enteredmarks" required="true">
</td>
</tr>
{% endfor %}
</tbody>
</table>
<input type="submit" class="ui primary button" id="submit_marks" value="Upload">
</form>
</div>
{% endblock %}
<script type="text/javascript" src="{% static 'globals/js/jquery.min.js' %}"></script>
<script type="text/javascript">
$(function() {
$("#entermarks").submit(function(event) {
event.preventDefault();
var friendForm = $(this);
var posting = $.post( friendForm.attr('action'), friendForm.serialize() );
// if success:
posting.done(function(data) {
alert('Upload Successful');
// window.location = "/academic-procedures/main/";
});
// if failure
posting.fail(function(data) {
alert('Failed');
// window.location = "/academic-procedures/main/";
});
});
});
</script>
{{ record }} gives no value at all, whereas List in views prints a list.
try this
{% for list_obj in record %}
{{list_obj|safe}}
{% endfor %}
or
{{record|safe}}
hope it helps for your problem