Django - Multiple Select Box - Save Changes to Database - mysql

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.

Related

django html: copy form input data and display in another page

I am trying to develop a delivery service web where users can input pickup and delivery address in the form and get the price online. if the price is fine, the user can click "place order" button which will navigate into another new page for user to fill in additional information, and importantly the previously input piackup and delivery addresses and the price will need to automatically shown somewhere in the new page.
I am new to django and html, and I have tried to created a simpler page serving the same purpose. Now I could do the first part of form filling, and the backend calculate based on the user input and return the calculation result (e.g. price). Now, I am wondering how to do the "navigation to another new page which will display the two input values and calculation result"
Main html:
<html>
<body>
<form method="POST" hx-post="{% url 'blog:post_list' %}" hx-target="#num_1" hx-target="#num_2" hx-target="#result">
{% csrf_token %}
<div>
<label>num_1:</label>
<input type="text" name="num_1" value="" placeholder="Enter value" />
</div>
<div>
<label>num_2:</label>
<input type="text" name="num_2" value="" placeholder="Enter value" />
</div>
<br />
<div id="num_1">{{ num_1 }}</div>
<br />
<div id="num_2">{{ num_2 }}</div>
<br />
<div id="result">{{ result }}</div>
<br>
<button type="submit">Submit</button>
</form>
<script src="https://unpkg.com/htmx.org#1.6.1"></script>
</body>
</html>
Child html:
<div>
<label>first_number:</label>
<span id="num_1"> {{ num_1 }} </span>
</div>
<div>
<label>second_number:</label>
<span id="num_2"> {{ num_2 }} </span>
</div>
<div>
<label>calculation_result:</label>
<span id="result"> {{ result }} </span>
</div>
view.py:
def post_list(request):
result = ""
num1 = ""
num2 = ""
if request.method == "POST":
num1 = request.POST.get('num_1')
num2 = request.POST.get('num_2')
result = int(num1) + int(num2)
if request.headers.get('Hx-Request') == 'true':
# return only the result to be replaced
# return HttpResponse(str(result))
return render(request, 'blog/post_list_snippet.html', {'num_1': num1,'num_2': num2,'result': result})
else:
return render(request, 'blog/post_list.html', {'num_1': num1,'num_2': num2,'result': result})

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

Passing list from views.py to template showing null value

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

Adding data into the database with django by pressing enter

I do not see what I am doing wrong when trying to add data into the database. When I am pressing the button Submit, nothing is entered in the database. The same happens when pressing the key enter.
Here is my html file.
<script>
$(document).keypress(function(event) {
if (event.keyCode == 13 || event.which == 13) {
alert('enter key is pressed');
event.preventDefault();
}
});
</script>
<div class="col-md-6 col-md-offset-3">
<form method="POST" action="">
<p>
{% csrf_token %}
<input type="hidden" value="{{post.id}}" />
<div class="col-xs-16" style="margin: 0; 0;padding: 3%;">
<label for="inputsm">Oracle</label>
<input class="form-control input-md" type="text" value="{{ post }}">
<input type="submit" value="Submit" style="display: none" /> {{ form.body }}
<button type="submit" value="Submit" class="btn btn-success">Submit</button>
</p>
</div>
</form>
</div>
Here is the views.py
def post_list(request):
posts = Post.objects.all()
category = Category.objects.all()
context = {
'posts':posts,
'cat':category,
}
return render(request, 'journal/post_list.html', context)
def add_post(request):
post = get_object_or_404(Post, pk=pk)
if request.method == "POST":
form = PostForm(request.POST or None)
if form.is_valid():
post = form.save(commit=False)
post.save()
return redirect('post_details', pk=post.pk)
return render(request, 'journal/post_list.html', {'post': post})
else:
form = PostForm()
context = {
"form": form,
}
return render_to_response('journal/post_list.html', context)
Does the form get submitted? If not, maybe try adding some javascript to submit the form, when the key is pressed
$("form").submit();

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