I want to make an attendance system that prevents each user to see the attendance that some users have taken. But in my case, the attendance that the other users take can be shown by every user. How can I prevent this part? These are my codes: Models.py
class ClassAttendance(models.Model):
Faculty_Name = models.CharField(max_length=200, null=True, blank=True)
Student_ID = models.CharField(max_length=200, null=True, blank=True)
firstname = models.CharField(max_length=200, null=True, blank=True)
lastname = models.CharField(max_length=200, null=True, blank=True)
date = models.DateField(auto_now_add = True, null = True)
time = models.TimeField(auto_now_add=True, null = True)
college = models.CharField(max_length=200, null=True, blank=True)
course = models.CharField(max_length=200, null=True, blank=True)
year = models.CharField(max_length=200, null = True)
section = models.CharField(max_length=200, null = True)
subject = models.CharField(max_length=200, null = True)
status = models.CharField(max_length=200, null = True, default='Absent')
def __str__(self):
return str(self.Student_ID + "_" + str(self.lastname) + "_" + str(self.date)+ "_" + str(self.subject))
class Faculty(models.Model):
user = models.OneToOneField(User, null = True, blank = True, on_delete= models.CASCADE)
firstname = models.CharField(max_length=200, null=True, blank=True)
lastname = models.CharField(max_length=200, null=True, blank=True)
college = models.CharField(max_length=200, null=True, choices=COLLEGE)
course = models.CharField(max_length=200, null=True, choices=COURSE)
year = models.CharField(max_length=200, null=True, choices=YEAR)
section = models.CharField(max_length=200, null=True, choices=SECTION)
subject = models.CharField(max_length=200, null=True, choices=SUBJECT)
def str(self):
return str(self.firstname + " " + self.lastname)
class Meta:
verbose_name_plural = "Faculties"
views.py
#login_required(login_url = 'login')
def takeClassAttendance(request):
if request.method == 'POST':
details = {
'college':request.POST['college'],
'course':request.POST['course'],
'year': request.POST['year'],
'section':request.POST['section'],
'subject':request.POST['subject'],
'faculty':request.user.faculty
}
if ClassAttendance.objects.filter(date = str(date.today()), college = details['college'], course = details['course'], year = details['year'], section = details['section'],subject = details['subject']).count() != 0 :
messages.error(request, "Attendance already recorded.")
return redirect('home')
else:
students = Student.objects.filter(college = details['college'], course = details['course'], year = details['year'], section = details['section'])
names = Recognizer(details)
for student in students:
if str(student.student_id) in names:
classattendance = ClassAttendance(Faculty_Name = request.user.faculty,
Student_ID = str(student.student_id),
lastname = str(student.lastname),
firstname = str(student.firstname),
college = details['college'],
course = details['course'],
year = details['year'],
section = details['section'],
subject = details['subject'],
status = 'Present')
classattendance.save()
else:
classattendance = ClassAttendance(Faculty_Name = request.user.faculty,
Student_ID = str(student.student_id),
lastname = str(student.lastname),
firstname = str(student.firstname),
college = details['college'],
course = details['course'],
year = details['year'],
section = details['section'],
subject = details['subject'],)
classattendance.save()
classattendances = ClassAttendance.objects.filter(date = str(date.today()),college = details['college'], course = details['course'], year = details['year'], section = details['section'],subject = details['subject'])
context = {"attendances":classattendances, "ta":True}
messages.success(request, "Attendance taking success")
return render(request, 'attendance_sys/attendance.html', context)
context = {}
return render(request, 'attendance_sys/home.html', context)
def facultyProfile(request):
faculty = request.user.faculty
form = FacultyForm(instance = faculty)
context = {'form':form}
return render(request, 'attendance_sys/facultyForm.html', context)
I expected that after the users take attendance, they are the ones that can see that information
You can filter the returned objects by request.user.faculty.
Related
89
I am new to Django.I am getting this error when i use many to many field
View
def add_ship(request):
if request.method=='POST':
m_namedriver = request.POST.get('m_namedriver')
driver_id = Driver.objects.get(driver_id=m_namedriver)
m_licensepl = request.POST.get('m_licensepl')
car_id = Car.objects.get(car_id=m_licensepl)
m_weightcoolbox = request.POST.get('m_weightcoolbox')
coolbox_id = Coolbox.objects.get(coolbox_id=m_weightcoolbox)
ship_date = request.POST.get('ship_date')
ship_time = request.POST.get('ship_time')
original = request.POST.get('original')
destination = request.POST.get('destination')
if shipping.objects.count() != 0:
ship_id_max = shipping.objects.aggregate(Max('shipping_id'))['ship_id__max']
next_ship_id = ship_id_max[0:2] + str(int(ship_id_max[2:6])+1)
else:
next_ship_id = "SP1000"
new_shipping = shipping.objects.create(
shipping_id = next_ship_id,
driver_id = driver_id,
car_id = car_id,
coolbox_id = coolbox_id,
ship_date = ship_date,
ship_time = ship_time,
original = original,
destination = destination,
)
new_shipping.save()
new_shipping.shipping.add(coolbox_id)
return render(request,'add_ship.html',{'message1':"Add shipping successful."})
driver_ship = Driver.objects.all()
car_ship = Car.objects.all()
coolbox_ship = Coolbox.objects.all()
return render(request,'add_ship.html',{'driver_ship':driver_ship,'car_ship':car_ship,'coolbox_ship':coolbox_ship})
#
type here
Models
class Coolbox(models.Model):
coolbox_id = models.CharField(max_length=40,primary_key=True)
medicine_name = models.ForeignKey(Medicine, on_delete=models.CASCADE, related_name="medicinename")
weight = models.FloatField(blank=True, null=True)
coolboxtemp_max = models.FloatField(blank=True, null=True)
coolboxtemp_min = models.FloatField(blank=True, null=True)
dimension = models.CharField(max_length=40)
d_measurement = models.CharField(max_length=40)
t_measurement = models.CharField(max_length=40)
total = models.FloatField(blank=True, null=True)
status = models.CharField(max_length=20, choices=STATUS, blank=True)
def __str__(self):
return f"{self.medicine_name}"
class shipping(models.Model):
shipping_id = models.CharField(max_length=15,primary_key=True)
driver_id = models.ForeignKey(Driver, on_delete=models.CASCADE, related_name="driverfk")
car_id = models.ForeignKey(Car, on_delete=models.CASCADE, related_name="carfk")
coolbox_id = models.ManyToManyField(Coolbox, related_name="coolboxfk")
ship_date = models.DateField(blank=True,null=True)
ship_time = models.TimeField(blank=True,null=True)
original = models.CharField(max_length=200)
destination = models.CharField(max_length=200)
def __str__(self):
return f"{self.shipping_id}: {self.driver_id}"
type here
I have a django project for student marks.
Models.py
class Registration(CMTracking):
student = models.ForeignKey(Student, on_delete=models.CASCADE)
academic_year = models.ForeignKey(AcademicYear, on_delete=models.CASCADE)
school = models.ForeignKey(School, on_delete=models.CASCADE)
grade = models.CharField(max_length=5, choices=Grade.choices)
school_class = models.ForeignKey(SchoolGradeClass, on_delete=models.CASCADE, blank=True, null=True)
last_year_result = models.PositiveSmallIntegerField(choices=RESULT.choices, blank=True, null=True)
last_grade = models.CharField(max_length=5, choices=Grade.choices, null=True)
date_of_join = models.DateField(null=True, blank=True)
type_of_registration = models.PositiveSmallIntegerField(choices=TypeOfRegistration.choices, default=0, null=True)
type_of_attendance = models.PositiveSmallIntegerField(choices=TypeOfAttendance.choices, null=True)
transfer_from = models.PositiveSmallIntegerField(choices=TransferFrom.choices, blank=True, default=1)
status = models.PositiveSmallIntegerField(choices=RequestStatus.choices, default=0)
class Exam(CMTracking):
fa_name = models.CharField(max_length=70, null=False)
en_name = models.CharField(max_length=70, null=False)
ar_name = models.CharField(max_length=70, null=False)
total_mark = models.DecimalField(max_digits=5, decimal_places=2, default=0)
exam_type = models.PositiveSmallIntegerField(choices=ExamType.choices)
academic_year = models.ForeignKey(AcademicYear, on_delete=models.CASCADE)
class ExamSubject(CMTracking):
exam = models.ForeignKey(to=Exam, on_delete=models.CASCADE)
subject = models.ForeignKey(to=SubjectMaster, on_delete=models.CASCADE)
teacher = models.ForeignKey(Staff, related_name='ExamSubjectList', on_delete=models.CASCADE) # Namavar
school_class = models.ForeignKey(SchoolGradeClass, on_delete=models.CASCADE, blank=True, null=True)
min = models.PositiveSmallIntegerField(null=True)
max = models.PositiveSmallIntegerField(null=True)
class MarkDescriptive(CMTracking):
subject = models.ForeignKey(ExamSubject, on_delete=models.CASCADE)
student = models.ForeignKey(Registration, related_name='mark_list_descriptive', on_delete=models.CASCADE)
goal = models.ForeignKey(to=SubjectGoalsMaster, on_delete=models.CASCADE)
point = models.FloatField(null=True, blank=True)
t2point = models.FloatField(null=True, blank=True)
forms.py:
class MarkDescriptiveModelForm2(forms.ModelForm):
student = forms.ModelChoiceField(queryset=Registration.objects.all().select_related('student__person').filter(school_id=106), required=False)
# student = forms.IntegerField() # only shows the id
goal = forms.ModelChoiceField(queryset=SubjectGoalsMaster.objects.all(), required=False)
point = forms.ChoiceField(choices=DescriptivePoint5.choices)
t2point = forms.ChoiceField(choices=DescriptivePoint5.choices)
class Meta:
model = MarkDescriptive
fields = ['id', 'student', 'point', 't2point']
Views.py:
#login_required()
#require_http_methods(['POST', 'GET', 'PUT'])
def mark_descriptive_update(request, exam_subject_id=None, goal_id=None):
subject = get_object_or_404(ExamSubject, id=exam_subject_id)
goal = get_object_or_404(SubjectGoalsMaster, id=goal_id)
MarkFormset = modelformset_factory(MarkDescriptive, form=MarkDescriptiveModelForm2, extra=0)
marks = subject.markdescriptive_set.all().select_related('subject__exam') \
.select_related('student__academic_year') \
.select_related('student__student__person') \
.select_related('goal').select_related('subject__subject').filter(goal=goal)
formset = MarkFormset(request.POST or None, queryset=marks)
add_url = reverse('add-class')
template = 'school/loaders/load_form.html'
form_template = 'school/pages/exam/mark_descriptive/formset.html'
context = {
# 'form': form,
'records': marks,
'subject': subject,
'goal': goal,
'formset': formset,
'template': template, 'form_template': form_template, 'add_url': add_url}
# if request.method == 'PUT':
if request.method == 'POST':
print(f'\n\n\nrequest is {request.method}\n')
print(f'formset data:{formset.data}')
if formset.is_valid():
print('formset is valid')
for form in formset:
updated_mark = form.save(commit=False)
updated_mark.subject = subject
updated_mark.goal = goal
updated_mark.modified_by = request.user
updated_mark.last_modified = datetime.now()
updated_mark.save()
print('*** \n Marks added succefully !\n***')
else:
print(' form not valid', formset.errors)
return render(request, form_template, context)
issue ::
student = forms.ModelChoiceField(queryset=Registration.objects.all().select_related('student__person').filter(school_id=106), required=False)
Takes too long to load student details I tried to override the form to get only students that are in the same exam but couldn't do that. and overall I do not need at all the student field to be as selection. a normal label of student name is totally enough as the data already populated and teacher will only enter the point.
I am working on a Django Project where I want to collect payment in Dollars from Applicants on the portal, and I don't know how to go about it. Though I have been following an online tutorial that shows how to do it but the result I am having is different with the recent error which says 'module' object is not callable.
Remember that I have tested my configured environment and also imported it into my views on top of the page.
Profile model code:
class Profile(models.Model):
applicant = models.OneToOneField(User, on_delete=models.CASCADE, null = True)
surname = models.CharField(max_length=10, null=True)
othernames = models.CharField(max_length=30, null=True)
gender = models.CharField(max_length=6, choices=GENDER, blank=True, null=True)
nation = models.CharField(max_length=255, choices=NATION, blank=True, null=True)
state = models.CharField(max_length=20, null=True)
address = models.CharField(max_length=200, null=True)
phone = models.CharField(max_length=16, null=True)
image = models.ImageField(default='avatar.jpg', upload_to ='profile_images')
def __str__(self):
return f'{self.applicant.username}-Profile'
Education/Referee Model code:
class Education(models.Model):
applicant = models.OneToOneField(User, on_delete=models.CASCADE, null = True)
qualification = models.CharField(max_length=60, choices=INSTITUTE, default=None, null=True)
instition = models.CharField(max_length=40, null=True)
reasons = models.CharField(max_length=100, null=True)
matnumber = models.CharField(max_length=255, null=True)
reference = models.CharField(max_length=100, null=True)
refphone = models.CharField(max_length=100, null=True)
last_updated = models.DateTimeField(auto_now_add=False, auto_now=True)
def __str__(self):
return f'{self.applicant}-Education'
Submitted Model code:
class Submitted(models.Model):
applicant = models.OneToOneField(User, on_delete=models.CASCADE, null=True)
application = models.UUIDField(primary_key = True, editable = False, default=uuid.uuid4)
confirm = models.BooleanField()
approved = models.CharField(max_length=20, null=True)
date = models.DateTimeField(auto_now_add=True)
def save(self, *args, **kwargs):
self.application == str(uuid.uuid4())
super().save(*args, **kwargs)
def __unicode__(self):
return self.applicant
def __str__(self):
return f'Application Number: {self.application}-{self.applicant}'
Scholarship Model code:
class Scholarship(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, null = True)
name = models.CharField(max_length=100, null = True)
description = models.CharField(max_length=200, null = True)
category = models.CharField(max_length=60, choices=INSTITUTE, default=None, null=True)
amount = models.FloatField()
date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return f'WASU Scholarship: {self.name}-{self.name}'
My View for printing slip:
def AppSlip(request):
check_submited = Submitted.objects.get(applicant=request.user)
check_education = Education.objects.get(applicant = request.user)
candidate_edu = check_education.qualification
scholarship = Scholarship.objects.get(category=candidate_edu)
context = {
'candidate_edu':candidate_edu,
'scholarship':scholarship,
}
return render(request, 'user/slip.html', context)
My view for applicant to fill form for payment which I want their Profile captured automatically in the form:
def scholarship_detail(request, pk):
data = Scholarship.objects.get(id=pk)
if request.method=='POST':
form = PaymentForm(request.POST)
if form.is_valid():
user = Profile.objects.get(applicant=request.user)
name= user.surname
email = form.cleaned_data['email']
amount = form.cleaned_data['amount']
phone = form.cleaned_data['phone']
context = {'applicant':name, 'email':email, 'amount':amount, 'phone':phone}
return process_payment(request, context)
else:
form = PaymentForm()
ctx={
'form':form,
'product':data,
}
return render(request, 'user/scholarship.html', ctx)
My form code for Payment: How can query logged in user profile and fill into name, email, phone, amount from Scholarship Model into amount form filled.
class PaymentForm(forms.Form):
name = forms.CharField(label='Your name', max_length=100)
email = forms.EmailField()
phone=forms.CharField(max_length=15)
amount = forms.FloatField()
View code for processing Payment (Where I am suspecting the error). Though I have configured my env using django-dotenv with the Flutterwave Secret Key in it.
#login_required(login_url='user-login')
def process_payment(request, newContext={}):
auth_token= dotenv('SECRET_KEY')
hed = {'Authorization': 'Bearer ' + auth_token}
data = {
"tx_ref":''+str(math.floor(1000000 + random.random()*9000000)),
"amount":amount,
"currency":"KES",
"redirect_url":"http://localhost:8000/callback",
"payment_options":"card",
"meta":{
"consumer_id":23,
"consumer_mac":"92a3-912ba-1192a"
},
"customer":{
"email":email,
"phonenumber":phone,
"name":name
},
"customizations":{
"title":"WASU Scholarship 2022",
"description":"Best store in town",
"logo":"https://getbootstrap.com/docs/4.0/assets/brand/bootstrap-solid.svg"
}
}
url = ' https://api.flutterwave.com/v3/payments'
response = requests.post(url, json=data, headers=hed)
response=response.json()
link=response['data']['link']
return link
My payment Response View:
#require_http_methods(['GET', 'POST'])
def payment_response(request):
status=request.GET.get('status', None)
tx_ref=request.GET.get('tx_ref', None)
print(status)
print(tx_ref)
return HttpResponse('Finished')
Anticipating your prompt answers. Thanks
This is my Toko Table
class Toko(models.Model):
nama_toko = models.CharField(max_length=30)
username = models.CharField(max_length=30)
image_banner = models.ImageField(upload_to='toko')
lokasi = models.CharField(max_length=30)
deskripsi = models.CharField(max_length=30)
status = models.CharField(max_length=30)
boolean= models.BooleanField(default=0)
def __str__(self):
return self.username
This is my Product Table
class Produk(models.Model):
nama_produk = models.CharField(max_length=30)
gambar = models.ImageField(upload_to='produk')
size = models.IntegerField(default=500)
deskripsi = models.CharField(max_length=200)
harga_resseler = models.IntegerField(default=0)
harga_agen = models.IntegerField(default=0)
harga_distributor = models.IntegerField(default=0)
harga_retail = models.IntegerField(default=0)
harga_hpp = models.IntegerField(default=0)
**This is my CartPaket **
class CartPaket(models.Model):
customer_name = models.CharField(max_length=30)
harga = models.IntegerField()
quantity = models.IntegerField(default=0)
total_berat = models.IntegerField(default=200)
subtotal = models.IntegerField(default=0)
total = models.IntegerField(default=0)
tanggal_pesan = models.DateTimeField(auto_now_add=True)
kota_customer_id = models.IntegerField(null=True)
kota_pelapak_id = models.IntegerField(null=True)
toko_id = models.ForeignKey(Toko, verbose_name='toko', on_delete=models.CASCADE, default=1)
produk_id = models.ForeignKey(Produk, verbose_name='produk', on_delete=models.CASCADE, default=1)
def __str__(self):
return self.customer_name
This is my views.py
if CartPaket.objects.filter(customer_name=get_user, produk_id=pro.id,
toko_id=get_toko.id).exists():
cart = CartPaket.objects.get(produk_id=pro.id, customer_name=get_user,
toko_id=get_toko.id)
cart.quantity += jumlah
cart.save()
else:
if jumlah != 0 or jumlah != '':
barang_distributor = Barang.objects.get(produk_id=pro.id, toko_id=get_toko.id)
cart = CartPaket(produk_id=pro.id, harga=barang_distributor.harga_jual,
toko_id=get_toko.id, customer_name=request.user.username,
quantity=jumlah, kota_customer_id=kota_customer_id,
kota_pelapak_id=kota_pelapak_id)
cart.total_berat = cart.quantity * cart.produk_id.size
cart.subtotal = cart.harga * cart.quantity
cart.save()
This is post request information
[1]: https://i.stack.imgur.com/OZhnU.png
This is the error i haved
[2]: https://i.stack.imgur.com/LYQja.png
Replace toko_id by toko_id__id. This way you are saying that the value after "=" is the id of the toko_id instance.
toko_id is an instance, like you defined in your models. Its id is toko_id.id
This may be a duplicate.
So I have:
class User(models.Model):
school = models.ForeignKey(School)
email = models.EmailField(max_length=254)
password = models.CharField(max_length=128)
firstname = models.CharField(max_length=50)
surname = models.CharField(max_length=50)
middlenames = models.CharField(max_length=100, blank=True)
utype = models.CharField(max_length=1, choices=(('a','Administrator'),('t','Staff'),('s','Student')))
lastlogin = models.DateTimeField(null=True)
active = models.BooleanField(default=True)
created = models.DateTimeField(auto_now_add=True)
class Staff(User):
# Some methods
class Student(User):
form = models.CharField(max_length=20)
parentemail = models.EmailField(max_length=254)
parentphone = models.CharField(max_length=20)
class Placement(models.Model):
student = models.ForeignKey(Student)
email = models.EmailField(max_length=254)
name = models.CharField(max_length=100)
company = models.CharField(max_length=100)
position = models.CharField(max_length=50)
house = models.CharField(max_length=50)
street = models.CharField(max_length=50)
town = models.CharField(max_length=50)
county = models.CharField(max_length=50)
postcode = models.CharField(max_length=8)
phone = models.CharField(max_length=20)
length = models.IntegerField(null=True)
category = models.CharField(max_length=50)
date = models.DateField(null=True)
state = models.CharField(max_length=1, choices=(('A','In progress'),('B','Confirmed'),('C','Completed')))
created = models.DateTimeField(auto_now_add=True)
class Visit(models.Model):
placement = models.ForeignKey(Placement)
staff = models.ForeignKey(Staff)
date = models.DateField(null=True)
feedback = models.CharField(max_length=1000)
confirmed = models.BooleanField(default=False)
created = models.DateTimeField(auto_now_add=True)
And I want to retrieve all Placements which do not have any Visits (and the Student belongs to a particular School).
My views
def placements(request):
if request.session['utype'] == 't':
context['user'] = Staff.objects.get(pk=request.session['user'])
if request.method == 'POST':
placements = context['placements'] = Placement.objects.filter(student__school=school)
for choice in visits:
placement = Placement.objects.get(pk=choice)
visit = placement.NewVisit(user, placement.date, '', False)
visit.save()
return redirect('workxp:visits')
else:
context['placements'] = Placement.objects.filter(student__school=school, visit_set=None)
return render(request, 'workxp/staff/placements.html', context)
This is what I have so far from looking at other questions, but it doesn't seem to work...
no_visits = Placement.objects.filter(student__school=school_object, visit_set=None)
If I give a related name to the placement field in Visit, it works. Why not visit_set?
You need to use visit_set to reference the reverse relation since it's one to many
no_visits = Placement.objects.filter(student__school=school_object, visit_set=None)
or if you were to specify a nice related name...
class Visit(models.Model):
placement = models.ForeignKey(Placement, related_name='visits')
...
no_visits = Placement.objects.filter(student__school=school_object, visits=None)