Taking Attendance in Django Python - django

I am trying to mark attendance. But I am not able to get the code. My submit should send the input to database for each student. Any suggestion for doing this in better way is welcome.
My models.py is as follows
It has Employee, Mentor and Student and below is the model where values can be changed.
class ClassName(models.Model):
class_name = models.CharField(max_length=20)
class_date=models.DateField(blank=True, null=True)
Mentor= models.ForeignKey(Mentor, related_name='class_mentor')
student = models.ManyToManyField(Student, related_name='class_student')
attendance = models.BooleanField(default=True)
def __str__(self):
return str(self.class_name)
Views.py : This is just to display the markattendance page. I am not able to figure out how to get the value and Post the value to database. Right now, I am fetching Students value from the Students table. I think I should be creating Classname Form and and display students. I was getting Internal server error.
def markattendance(request):
students = Student.objects.all()
return render(request, 'home/markattendance.html',
{'students': students})
markattendance.html : On clicking submit, the attendance should be marked.
{% extends 'home/index.html' %}
{% block content %}
<div class="container-fluid">
<div>
<div class="card-body">
<div class="table-responsive">
<table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">
<thead>
<tr>
<th>Name</th>
<th>Class</th>
<th>Attendance</th>
</tr>
</thead>
<tbody>
{% for students in students %}
{% ifequal students.Men_name|stringformat:"s" user.username %}
<tr>
<td>{{ students.Student_name }}</td>
<td>{{ students.Student_Class }}</td>
<td>
<label class="switch">
<input id="toggle-slider_position()" type="checkbox">
<span class="slider round"></span>
</label>
</td>
</tr>
{% endifequal %}
{% endfor %}
</tbody>
</table>
</div>
<br/>
<div class="row" >
<div class="col-sm-4"></div>
<div class='col-sm-4' align="center">
<div class="form-group">
<div class='input-group date' id='datetimepicker1'>
<input type='text' class="form-control" />
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
<button class="btn btn-lg">Submit</button>
</div>
<div class="col-sm-4">
</div>
</div>
<br/><br/><br/><br/><br/>
</div>
</div>
</div>
{% endblock %}
Please help me out. Any suggestion is welcome.

Related

how can ı submit more than one row in django view with table form

ı wanna submit more than one record but in that code only first student can be record how can ı add more than one record in django view ı am prety new in django can anyone help about that table image
thats the model.py
class GonulluOgrenciDevamsizlik(models.Model):
ogrenci_dersi = models.ForeignKey('Ogrenci', null=True, on_delete=models.SET_NULL)
gonulu = models.ForeignKey('Gonullu', null=True, on_delete=models.SET_NULL)
devamsizlik = models.BooleanField(verbose_name="Devamsızlık Bilgisi",blank=True, default=False)
sinif = models.ForeignKey('SinifListe', null=True, on_delete=models.SET_NULL)
olusturma_tarihi = models.DateTimeField(auto_now_add=True, verbose_name='Oluşturma Tarihi')
guncelleme_tarihi = models.DateTimeField(auto_now=True)
class Meta:
ordering = ['-devamsizlik']
verbose_name = 'Devamsızlık'
verbose_name_plural = 'Devamsızlıklar'
def __str__(self):
return self.gonulu.ad + ' ' + self.gonulu.soyad
here is my view: in view ı had been add required foreign keys for my table and then try to save coming post data from table form.
def ogrencidevamsizlik(request, id):
details = "hesabim/ogrenci-devamsizlik.html"
siniflar = SinifListe.objects.filter(gonullu__gonullu__email=request.user.email)
ogrenci = SinifDetay.objects.filter(sinif__gonullu__gonullu__email=request.user.email)
gonulu = GonulluDersleri.objects.get(gonullu__email__iexact=request.user.email, id=id)
gonulluler = Gonullu.objects.get(email__iexact=request.user.email)
ders = GonulluDersleri.objects.filter(gonullu__email=request.user.email, id=id)
devamsizliklar = SinifDetay.objects.filter(sinif__gonullu__gonullu__email=request.user.email, sinif__gonullu__id=id)
if request.method == 'POST':
form = DevamsizlikDetayForm(request.POST, request.FILES)
if form.is_valid():
form.save()
messages.success(request, 'Devamsızlıklar başarılı bir şekilde eklendi.')
return redirect('gonullu-siniflar')
else:
messages.error(request, 'Devamsızlık bilgilerinizdeki zorunlu alanları eksiksiz doldurmalısınız.')
else:
form = DevamsizlikDetayForm()
context = {'devamsizliklar': devamsizliklar,
'gonulu': gonulu,
'ders': ders,
'form': form,
'ogrenci': ogrenci,
'siniflar': siniflar,
'gonulluler': gonulluler}
return render(request, details, context)
and here is my table: in table ı try to add devamsizlik area for each student , gonulu , ogrenci and sinif ıd are already coming with views info but devamsizlik will submited by the gonullu so ı made a for loop for all student but when ı submit only first one can be submit thats the promlem
<form class="" novalidate method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{ form.title }}
<div class="row justify-content-center">
<div class="col-12 col-md-9 mt-3 ">
<div class="font-weight-bold align-center">Gönüllü Dersi :
{% for x in ders %}
{{ x.gonullu }} {% if x.birinci_ders != null %} {{ x.birinci_ders }} {{ x.birinci_ders_seviye }} {% endif %}
{% endfor %}
</div>
</div>
</div>
<div class="row justify-content-center">
<table class="table table-hover">
<thead>
<tr data-toggle="collapse" data-target="#accordion" class="clickable">
<th scope="col">Id</th>
<th scope="col">Öğrenci</th>
<th scope="col">Sınıf</th>
<th scope="col">Aktif</th>
<th scope="col">Devamsızlık</th>
</tr>
</thead>
<tbody>
{% for y in devamsizliklar %}
<tr>
<td id="accordion" class="collapse">{{ y.id }}</td>
<td id="accordion" class="collapse">{{ y.ogrenci }}</td>
<td id="accordion" class="collapse">{{ y.sinif }}</td>
<td id="accordion" class="collapse">{{ y.aktif }}</td>
<td id="accordion" class="collapse">
<div class="form-group row">
<div class="col-sm-10 col-md-7">
<input data-handle-width="20" data-label-width="1" data-size="mini"
{{ form|validation_class:"devamsizlik" }} id="devamsizlik" name="devamsizlik"
{% if form.devamsizlik.value %}checked{% endif %} class="form-control swich-check"
type="checkbox">
{{ form.devamsizlik|f_errors }}
</div>
</div>
<div class="form-group row" style="visibility: hidden; display: none">
<label for="gonulu" class="col-sm-2 col-md-5 col-form-label">Gönüllü*</label>
<div class="col-sm-10 col-md-7">
<select class="custom-select my-1 mr-sm-2 {{ form|validation_class:"gonulu" }}" name="gonulu"
id="gonulu" required>
<option value="{{ gonulu.gonullu.pk }}" selected="selected">{{ gonulu.gonullu|safe }}</option>
</select>
{{ form.gonulu|f_errors }}
</div>
</div>
<div class="form-group row" style="visibility: hidden; display: none">>
<label for="ad" class="col-sm-2 col-md-5 col-form-label">Öğrenci*</label>
<div class="col-sm-10 col-md-7">
<select class="custom-select my-1 mr-sm-2 {{ form|validation_class:"ogrenci_dersi" }}" name="ogrenci_dersi"
id="ogrenci_dersi" required>
<option value="{{ y.ogrenci.ogrenci.pk }}" selected="selected">{{ y.ogrenci.ogrenci|safe }}</option>
</select>
{{ form.ogrenci_dersi|f_errors }}
</div>
</div>
<div class="form-group row" style="visibility: hidden; display: none">>
<label for="ad" class="col-sm-2 col-md-5 col-form-label">Sınıf</label>
<div class="col-sm-10 col-md-7">
<select class="custom-select my-1 mr-sm-2 {{ form|validation_class:"sinif" }}" name="sinif"
id="sinif" required>
{% for x in siniflar %}
<option value="{{ x.pk }}" selected="selected">{{ x|safe }}</option>
{% endfor %}
</select>
{{ form.sinif|f_errors }}
</div>
</div>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<!--submit-->
<div class="row justify-content-center">
<button type="submit" name="save" value="save"
class="btn btn-primary mb-2 float-left bg-c b-0 rounded-0">
Devamsızlık bilgilerimi güncelle
</button>
</div>
</form>
And thats is the form.py
class DevamsizlikDetayForm(forms.ModelForm):
class Meta:
model = GonulluOgrenciDevamsizlik
fields = '__all__'

save() prohibited to prevent data loss due to unsaved related object 'user'

i am trying to save data in a table when a user click the checkout button of add to cart but it is showing me the above mention error i am unable to understand and one more thing is happening when i logout my the cart which i saved also got erased is it shomehow related to that i don't know
here is my views.py for checkout button
class Checkout(View):
def post (self, request,):
user = request.session.get('user')
ids = (list(request.session.get('cart').keys()))
sections = Section.get_sections_by_id(ids)
for section in sections:
order = Order(user = User(id=user),
section = section,
price = section.price,
)
order.save()
my views.py for cart.html
class Cart(View):
def get (self, request):
ids = (list(request.session.get('cart').keys()))
sections = Section.get_sections_by_id(ids)
print(sections)
return render(request, 'cart.html', {'sections': sections})
my urls.py
urlpatterns = [
path('cart/', Cart.as_view(),name='cart'),
path('Check-Out/', Checkout.as_view(),name='checkout'),
]
my cart.html
{% extends 'base.html' %}
{% load static %}
{% load cart %}
{% load custom %}
{% block head %}
<link rel="stylesheet" href="{% static 'css/cart.css' %}">
{% endblock %}
{% block content %}
<div class="container jumbotron">
<section>
<h1>My cart</h1>
<table class="table">
<thead>
<tr>
<th scope="col">S.no</th>
<th scope="col">Subject</th>
<th scope="col">Section</th>
<th scope="col">Teacher</th>
<th scope="col">Duration</th>
<th scope="col">Price</th>
</tr>
</thead>
{% for section in sections%}
<tbody style="margin-bottom: 20px;">
<tr>
<th scope="row">{{forloop.counter}}</th>
<td>{{section.subject.name}}</td>
<td>{{section.title}}</td>
<td>{{section.teacher}}</td>
<td>{{section.content_duration}}</td>
<td>{{section.price|currency}}</td>
</tr>
</tbody>
{% endfor %}
<tfoot>
<tr>
<th> Total</th>
<th></th>
<th></th>
<th></th>
<th></th>
<th>{{sections|total_price:request.session.cart|currency}}</th>
</tr>
<hr>
</tfoot>
</table>
<button type="button" data-toggle="modal" data-target="#exampleModal" style="float: right; margin-left:5px" class="btn btn-outline-primary">Check Out</button>
<button type="button" style="float: right; margin-left:5px" class="btn btn-info">Back To Site</button>
</tfoot>
</section>
</div>
<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Please Verify</h5>
<input type="button"class="btn-close btn-link" style="text-decoration:none; border:none; font-size:20px;" data-dismiss="modal" aria-label="Close" value="X">
</div>
<div class="modal-body">
<form action="{% url 'transactions:checkout' %}" method="Post">
{% csrf_token %}
<input type="submit" class="btn float-right btn-primary" value='Go Ahead'>
</form>
</div>
</div>
</div>
</div>
{% endblock %}
and my models.py
class Order(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE,)
section = models.ForeignKey(Section, on_delete=models.CASCADE )
price = models.FloatField(blank=False)
update_at = models.DateTimeField(auto_now=True, editable=False)
def placeorder(self):
self.save()
please help if you can an
The issue caused by this line:
order = Order(user = User(id=user)
Using User(id=user) means you want to create an unsaved User and use it in an unsaved Order and then saving the order, but this will not work because you haven't saved the User yet, as mentioned by the error.
You can just simply just use the existing user in the order like this:
order = Order(user=user, section=section, price=section.price)
order.save()

Django shopping cart update

I am trying to send slg (as quanty when update shopping cart):
{% for item in myCart.values %}
<tr>
<td class="product-col">
<img src="/media/{{item.image}}" alt="">
<div class="pc-title">
<h4>{{item.name}}</h4>
<p>${{item.price}}</p>
</div>
</td>
<td class="quy-col">
<div class="quantity">
<div class="pro-qty">
<input type="number" min="1" name="slg[{{item.id}}]" value="{{item.slg}}">
</div>
</div>
</td>
<td class="size-col"><h4>Size M</h4></td>
<td class="total-col"><h4>${% widthratio item.price 1 item.slg %}</h4></td>
<td class="total-col">Delete</td>
</tr>
{% endfor %}
This is my view, i am trying to get data form templates but it's not work
def updateCart(request):
slg = request.POST['slg']
return render(request, 'home/check.html', {'myCart': slg})
I don't see the section about the way you submit the data. You might want to build a form
like below
<form action="/your-name/" method="post">
<label for="your_name">Your name: </label>
<input type="submit" value="OK">
</form>
and post the data so when you check the request.POST that it has some data in it.
With your code, I don't see any data being posted.

How to create such a table with checkbox in django?

I want to have a table with a checkbox on each row with Django as shown in the image. My Django view.py, models.py and HTML file are mentioned below. How this can be done? Is there any built-in function in Django or what?
Table with check box
I have models file as:
class AppsDescription(db.Model):
aws_response = aws_list_conf_api_call()
CHOICES = [("yes", "YES"),
("no", "NO")]
OPTIONS = list()
for apps in aws_response:
OPTIONS.append(('{name1}'.format(name1=apps.lower()), '{name2}'.format(name2=apps)), )
name = db.CharField(max_length=256)
description = db.TextField()
plan_to_migrate = db.CharField(choices=CHOICES, max_length=256)
# app_names = MultiSelectField(choices=OPTIONS)
def __str__(self):
return self.name
My views.py as
def createapp(request):
# import ipdb; ipdb.set_trace()
form = DashboardForm()
if request.method == "POST":
form = DashboardForm(request.POST)
list_of_inputs = request.POST.getlist("inputs")
if form.is_valid:
form.save(commit=True)
return HttpResponseRedirect(reverse("aws:createapp"))
server = aws_server_list_conf()
return render(request, "createapp.html", {'server':server, 'form': form})
My html file as
<form method="POST">
{{form.as_p}}
<table>
<tr>
<th>Select</th>
<th>Agent ID</th>
<th>Configuration ID</th>
<th>Host Name</th>
<th>OS Name</th>
<th>OS Version</th>
<th>Source</th>
<th>Time of Creation</th>
<th>Type</th>
</tr>
{% for apps in server %}
<tr>
<td><input type="checkbox" name="" value=""></td>
{% for k,v in apps.items %}
<td>{{ v }}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
{% csrf_token %}
<input type="submit" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal" name="" value="submit">
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<div class="alert alert-success alert-dismissible">
<a class="close" data-dismiss="modal" aria-label="close">×</a>
<strong>Success!</strong> App information stored Successfully.
</div>
</div>
</div>
</form>
I want to have a table with checkbox on each row with django as shown in the image.
Your HTML file needs to look like this:
<form method="POST">
{{form.as_p}}
<table>
<tr>
<th>Select</th>
<th>Agent ID</th>
<th>Configuration ID</th>
<th>Host Name</th>
<th>OS Name</th>
<th>OS Version</th>
<th>Source</th>
<th>Time of Creation</th>
<th>Type</th>
</tr>
{% for apps in server %}
<tr>
{% for k,v in apps.items %}
<td><input type="checkbox" name="selected_options" value="v.id"></td>
<td>{{ v }}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
{% csrf_token %}
<input type="submit" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal" name="" value="submit">
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<div class="alert alert-success alert-dismissible">
<a class="close" data-dismiss="modal" aria-label="close">×</a>
<strong>Success!</strong> App information stored Successfully.
</div>
</div>
</div>
</form>

Django template queryset.example_set.all() showing different primary key

{% for n in medrec %}
<tr>
<td>{{ n.patient.pk }}</td>
<td>{{ n.patient.name }}</td>
<td>
<div class="ui grid">
<form class="ui form" id="mform{{ n.id }}" action="/mbill/" method="post">
{% csrf_token %}
<input value="{{ n.pk }}" type="hidden" name="pk">
{% for m in n.med_set.all %}
<div class="row">
<div class="eight wide column">{{ m.medicine }}</div>
<div class="eight wide column">
<div class="field"><input name="{{ m.medicine.id }}" type="text"></div>
<h5>{{ m.medicine.quantity }} left</h5>
</div>
</div>
{% endfor %}
</form>
</div>
</td>
<td class="right aligned">
<button type="submit" class="ui button green" form="mform{{ n.id }}" id="mbill">bill</button>
</td>
</tr>
{% endfor %}
I am trying to access pk of foreign keys of medrec or n. but instead of real pk it show 1,2,3... every time
the n.medicine.id gives 1,2,3... instead of the real 3,4,5 is there a work around for this?
class Medicine(models.Model):
medicalrec = models.ForeignKey(MedicalRec,related_name='med_set')
medicine = models.ForeignKey(Stock,related_name='stock_set')
stockpk = models.IntegerField()
class MedicalRec(models.Model):
patient = models.ForeignKey(Patient)
date = models.DateField()
disease = models.TextField()
treatment = models.TextField()
billed = models.BooleanField()