Reputation: 99
I am creating a student attendance system using django. I am fetching all student's names from the student database into an HTML table and updating information about students to django model.
This is my view.py to get data
def attendanceFill (request, subject):
context = ''
ad_standard = request.session.get('standardO')
subjects = CustomStudent.objects.filter(className__name__contains = ad_standard, subjectName__subjects__contains = subject)
# attendanceForm = Attendance(request.POST or None, instance=subjects)
print(ad_standard)
print(subject)
print(subjects)
context = {'subjects' : subjects}
if request.method == 'POST':
student = request.POST
print(student)
return render(request, 'teacher/attendance_fill.html', context)
This is my HTML template for data handling.
<div class="container">
<div class= "row mt-4">
<form action="" method="POST">
{% csrf_token %}
<table>
{% for student in subjects %}
<tr>
<td name= 'student'><p class="student-name" id="student-name">{{ student.sname }}</p></td>
<td>
<input type="checkbox" name="attendance" id="attendance">
</td>
</tr>
{% endfor %}
<tr>
<td>
<button type="button" name="checked" id = "checked" class="btn btn-outline-dark mb-4 shadow" style="border-radius:25px;">Submit</button>
</td>
<td></td>
</tr>
</table>
</form>
</div>
</div>
This is jquery function I am using to capture data.
var formData = new FormData()
$(document).ready(function(){
$("#checked").click('click', function(){
$students = document.getElementsByClassName('student-name').textContent;
$attendance = $('#attendance').val()
console.log($students)
console.log($attendance)
})
})
I have tried $('student-name').val()
to get value for all students but it returns blank. Nothing is captured with this method.
I wish capture all data and update it into attendance model.
This are my models:
# Custom Student Table
class CustomStudent(models.Model):
_id = models.AutoField
sname = models.CharField(max_length = 50)
slname = models.CharField(max_length = 50)
admissionNo = models.CharField(default= "", max_length=50)
parentName = models.CharField(default= "", max_length=100)
emerContact = models.CharField(default= "", max_length=50)
contactNo = models.CharField(default= "", max_length=50)
className = models.ForeignKey(Standard, on_delete=models.DO_NOTHING)
subjectName = models.ManyToManyField(Subject)
Year = models.CharField(default="", max_length=5)
email = models.CharField(default="", max_length=60)
address = models.CharField(default="", max_length=250)
def __str__(self):
# return str(self.slname)
return str(self.sname)
AttendenceChioces = [
('Y', 'Yes'),
('N', 'No')
]
# Student Attendance Table
cla
AttendanceStudent(models.Model):
attendace_id = models.AutoField(primary_key= True)
student = models.ForeignKey(CustomStudent, on_delete=CASCADE)
attendace = models.CharField(max_length = 50, choices=AttendenceChioces)
date = models.DateField(auto_now= True)
teacher = models.CharField(max_length=255)
def __str__(self):
return str(self.sname)
Is there any other efficient way to submit attendance data into database. I have tried capturing all data using jquery but it returns blank.
UPDATE:
I have figured out proper way to send data but issue is django is not receiving any data in view funtion. I have created a view function to process data as my current view function attendancefill
cannot process url without subject
value.
def attendanceFilled(request):
print(request.POST)
if request.method == 'POST':
print (request.POST)
return JsonResponse({'data' : request.POST}, status=200)
return render(request, 'teacher/attendance_st.html')
I have verified via console.log and chrome DevTools tat ajax is sending data. But in django there is no data. I have tried printing new data at all points in new view function. It always returns a empty dict.
This is my updated jquery:
var value = []
$(document).ready(function(){
$("#checked").click('click', function(){
csrf = $("input[name=csrfmiddlewaretoken]").val();
value.push({'csrfmiddlewaretoken' : '{{ csrf_token }}'})
$('#attendance_table tr').each(function(a,b){
$student = $('.student-name', b).text();
$present = $('#attendance', b).prop('checked');
value.push({Student : $student, Present : $present})
})
var datatoadd = JSON.stringify(value);
document.getElementById("demo").innerHTML = datatoadd;
console.log(datatoadd)
$.ajax({
type: "POST",
url: '{% url "attendanceFilled" %}',
data: datatoadd,
cache: false,
processData: false,
contentType: false,
success: function(){
alert('Attendance submitted')
},
error: function(xhr, errmsg, err){
console.log(xhr.status + ":" + xhr.responseText)
alert('Attendance Failed to Submit! Please contact adminitstrator with your issue!')
}
})
})
})
my path in urls:
path('subject/<slug:subject>/', views.attendanceFill, name="subject"),
path('attendanceFilled', views.attendanceFilled, name="attendanceFilled"),
I am only posting required URLs here my URL file is too big.
Upvotes: 1
Views: 1389
Reputation: 540
@Sahil Mohile- Your model needs some clean-up.
class StudentAttendance(models.Model):
attendance_id = models.AutoField(primary_key= True)
student = models.ForeignKey(CustomStudent, on_delete=CASCADE,db_index=True)
attendace = models.CharField(max_length = 20, choices=AttendenceChioces)
date = models.DateField(auto_now= True)
teacher = models.ForeignKey(settings.AUTH_USER_MODEL)#Dont call it #tname, explicit is better than implicit.
def __str__(self):
return str(self.sname)
Now. my main point. Attendance record is tied to a Term/Semester. How about you create a Semester Table. Tie the student attendance with a specific semester/term
import datetime
from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import models
def current_year():
return datetime.date.today().year
def max_value_current_year(value):
return MaxValueValidator(current_year())(value)
class Semester(models.Model):
name = models.CharField(max_length=50)
year = models.PositiveIntegerField(
default=current_year(), validators=[MinValueValidator(1984), max_value_current_year])
.........
e.g Fall 2020
class StudentAttendance(models.Model):
attendance_id = models.AutoField(primary_key= True)
semester = models.ForeignKey(Semester,db_index=True)
student = models.ForeignKey(CustomStudent, on_delete=CASCADE,db_index=True)
attendace = models.CharField(max_length = 20, choices=AttendenceChioces)
date = models.DateField(auto_now= True)
teacher = models.ForeignKey(settings.AUTH_USER_MODEL)#Dont call it #tname, explicit is better than implicit.
Also, I predict that there might be a situation where you will be asked to present the number of present days for a specific student in a specific semester. Something to think about.
I am a bit confused. You are capturing the data but where are you making the ajax POST? You need to share the POST request
var formData = new FormData()
$(document).ready(function(){
$("#checked").click('click', function(){
$students = document.getElementsByClassName('student-name').textContent;
$attendance = $('#attendance').val()
console.log($students)
console.log($attendance)
})
})
Shouldn't you be doing the following too
$.ajax({
type: "POST",
url: 'your url',
data: {
#your data
csrfmiddlewaretoken: csrf_token
},
success:function(response){
},
error:function(error){
}
});
Upvotes: 1