Passing list from views.py to template showing null value - html

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

Related

Getting bootstrap dropdown value return to work in flask

I am trying to get a value (player) from the dropdown select. Once I click the dropdown button, I want the value 'player' to get sent to flask and render the new player's image on the website.
HTML:
<form method="POST">
<div class="input-group">
<select class="custom-select" id="inputGroupSelect04" name="player" value="{{ player }}">
{% for key, value in team.items() %}
<option value={{ value }}>{{ value }}</option>
{% endfor %}
</select>
<div class="input-group-append">
<button class="btn btn-outline-secondary" type="submit">Select</button>
</div>
</div>
</form>
<img src="/static/{{ player }}.png" alt="{{ player }}">
Flask:
#app.route("/", methods=['POST', 'GET'])
def main_page():
player = okc[1628983]
if request.method == "POST":
print("this posted")
player = request.form.get('player')
print(request.form.get('player'))
return render_template("index.html", team=okc, player=player)
return render_template("index.html", team=okc, player=player)
instead of your:
player = request.form.get('player')
you can try this:
player = request.form['player']
Button wasn't posting - changed type from button to submit

Extracting data using ajax from a database in django and then display it in view

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;
}
});
});

HTML form - only works on a single button in a loop

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.

Django - Multiple Select Box - Save Changes to Database

I was able to get a multiple select box working for edit mode:
<section class="container">
<div>
<select id="leftValues" size="5" multiple></select>
</div>
<div>
<input type="button" id="btnLeft" value="<<" />
<input type="button" id="btnRight" value=">>" />
</div>
<div>
<select id="rightValues" size="4" multiple>
{% for device in devices %}
<option>{{ device }}</option>
{% endfor %}
</select>
</div>
</section>
<div>
<input type="text" id="txtRight" />
</div>
</section>
<button type="submit" id="save">Save Changes</button>
<!--button type="cancel">Cancel</button-->
Maintenance Page</button>
</form>
<link rel="stylesheet" href="{% static 'css/msb.css' %}">
<script>
$("#btnLeft").click(function () {
var selectedItem = $("#rightValues option:selected");
$("#leftValues").append(selectedItem);
});
$("#btnRight").click(function () {
var selectedItem = $("#leftValues option:selected");
$("#rightValues").append(selectedItem);
});
$("#rightValues").change(function () {
var selectedItem = $("#rightValues option:selected");
$("#txtRight").val(selectedItem.text());
});
But when I select the save button, after making changes to the table, again in the template, edit_maintenance.html, it does not feed into the database.
The code in the views.py that relates to this is as follows:
def edit_maintenance(request, id):
license_key = Maintenance.objects.get(id=id)
maintenance_form = MaintenanceForm(instance=license_key)
devices = Devices.objects.filter(maintenance = id)
if request.method == 'POST':
print(request.POST)
maintenance_form = MaintenanceForm(request.POST, instance=license_key)
if maintenance_form.is_valid():
maintenance_form.save()
# return redirect('maintenance:edit_maintenance', id)
args = {
'maintenance_form' : maintenance_form,
'devices' : devices
}
return render(request, 'inventory/edit_maintenance.html', args)
I'm still fairly new to this so any tips, examples, would be great.
sadly, this was a novice's mistake. I re-ran makemigration and migrate and the functionality works just fine now ... for delete. Now I need to work on the code for adding.

How to pass Json value and get respective data

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];
}