Reputation: 418
I have a question about saving a list in Django database. Let me explain my problem, is pretty complex so I hope you understand that. At the base, I have a list of values (called learning objectives) where each student will have a grade from 1 to 5. Now, the idea is that the teacher, to give the evaluation, will press a checkbox corresponding to each grade and the database will create some sort of record to store the student's evaluation.
models.py
GRADING_VALUE = (
('1', '1'),
('2', '2'),
('3', '3'),
('4', '4'),
('5', '5'),
)
class Grading(models.Model):
value = models.CharField(max_length=10, choices=GRADING_VALUE)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.value
class LearningObjective(models.Model):
name = models.CharField(max_length=300)
mission = models.ForeignKey(Mission, on_delete=models.DO_NOTHING)
grading = models.ForeignKey(
Grading, on_delete=models.DO_NOTHING, blank=True, null=True)
note = models.ForeignKey(
Note, on_delete=models.DO_NOTHING, null=True, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.name
class MissionEntry(models.Model):
mission = models.ForeignKey(Mission, on_delete=models.DO_NOTHING)
log_entry = models.ForeignKey(LogEntry, on_delete=models.DO_NOTHING)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return str(self.mission) + ' ' + str(self.log_entry)
class LearningObjGradingNote(models.Model):
learning_objective = models.ForeignKey(
LearningObjective, on_delete=models.DO_NOTHING, blank=True, null=True)
grade = models.ForeignKey(
Grading, on_delete=models.DO_NOTHING, blank=True, null=True)
note = models.ForeignKey(
Note, on_delete=models.DO_NOTHING, blank=True, null=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
views.py
def mission_test(request, pk):
mission = Mission.objects.get(id=pk)
learning_obj = LearningObjective.objects.filter(mission_id=mission)
grading = Grading.objects.all()
aircrafts = Aircraft.objects.all()
aerodromes = Aerodrome.objects.all()
function_type = FunctionType.objects.all()
students = Student.objects.all()
instructors = Instructor.objects.all()
context = {
'mission': mission,
'learning_obj': learning_obj,
'grading': grading,
'aircrafts': aircrafts,
'aerodromes': aerodromes,
'function_type': function_type,
'students': students,
'instructors': instructors
}
if request.method == 'POST':
aircraft = request.POST.get('aircraft')
adep = request.POST.get('adep')
ades = request.POST.get('ades')
date = request.POST.get('date')
etd = request.POST.get('etd')
ata = request.POST.get('ata')
function_type_obj = request.POST.get('function_type')
student = request.POST.get('student')
instructor = request.POST.get('instructor')
note = request.POST.get('note')
comment = request.POST.getlist('comment')
grade = request.POST.getlist('grade')
comment_list = []
for com in comment:
comment_list.append(com)
print(comment_list)
grade_list = []
for g in grade:
grade_list.append(g)
print(grade_list)
lo_list = []
for lo in learning_obj:
lo_list.append(lo)
print(lo_list)
try:
log_entry = LogEntry.objects.create(aircraft_id=aircraft, adep_id=adep, ades_id=ades, date=date, etd=etd,
ata=ata, function_type_id=function_type_obj, student_id=student, instructor_id=instructor, note=note)
print(log_entry)
learning_objective = LearningObjective(
grading_id=grade_list, note_id=comment_list, learning_objective=learning_obj)
learning_objective.save()
mission_entry = MissionEntry.objects.create(
log_entry_id=log_entry, mission_id=mission)
learning_obj.save()
log_entry.save()
mission_entry.save()
messages.success(request, "Successfully Added New Flight")
return HttpResponseRedirect(reverse('mission:mission_test', kwargs={'pk': pk}))
except:
messages.error(request, "Failed to Add New Flight")
return HttpResponseRedirect(reverse('mission:mission_test', kwargs={'pk': pk}))
return render(request, 'mission/mission_test.html', context)
Now, the part where I am having problem (let alone I know there are other things to be fixed, but I am on it) is in saving the list of grading and comments (which can be also empty) for each learning objective. How can I do that with a for loop? I hope I was clear enough.
Upvotes: 0
Views: 402
Reputation: 292
form.html
{% for row in locality %}
<div class='locality_field locality_style'>
<div class="col-xs-4 col-sm-8 custom_TopmMar">
<input type="text" class="form-control" name="locality_name" id="exist_locality_{{ row.Locality_Id }}" data-localityId='{{ row.Locality_Id }}' value='{{ row.Locality_Name }}'>
</div>
<div class="col-xs-2 col-sm-4 custom_TopmMar">
<a href="javascript:void(0)" {% if not row.locality_count %} class="border_btn red_btn_bg red_border btn_del_locality" data-localityId="{{ row.Locality_Id }}" {% else %} class="border_btn red_btn_bg red_border disabled" title="There are Stores associated to this locality, so it cannot be deleted"{% endif %}><i class="fa fa-times" aria-hidden="true"></i></a>
</div>
</div>
{% endfor %}
script.js
-------------this is what you have to do --------------------
let locality_list = []
let locality_names = $('input[name="locality_name"]');
for (const locality of locality_names) {
locality_list.push({
locality_id: $(locality).data("localityid"),
locality_name: $(locality).val(),
});
}
$.ajax({
dataType: "json",
url: `/a/md/s_lo/${$("#city_id").val()}`,
type: "post",
// beforeSend: function () {
// $("#cover-spin").fadeIn();
// },
data: {
csrfmiddlewaretoken: $(
'#edit_city_locality_form input[name="csrfmiddlewaretoken"]'
).val(),
city_id: $("#city_id").val(),
city_name: $("#city_name").val(),
locality_list: JSON.stringify(locality_list),
},
success: function (response) {
if (response) {
location.reload();
}
},
});
-------------this is what you have to do --------------------
views.py
def save_locality(request):
'''
saving locality data
'''
try:
locality_list = request.POST.get('locality_list')
city_name = request.POST.get("city_name")
city_id = request.POST.get("city_id")
return data
except Exception as e:
I'm not posting whole code here. Only the code you need for reference Please like it, if this helps you
Upvotes: 1