Search and Retrieve the data from the database in Django - django

I wanted to search and retrieve the data from the database in the Django I have saved the data which comes from the API endpoint to the database and have created few labels in the html based on which it will filter the matched data from the database
It rather than searching the matched value but its adding another column with searched value.
For instance: If I search "vendorname" as Pepsi it should reflect the table row which containing Pepsi rather than it creating another column with the value as Pepsi.
I don't know where I'm going wrong. I have lot of columns from the database and 6 labels just I have added few only here. Thanks in Advance
I have created two database here one for filter another for API data:
models.py:
//filter
class Userbase(models.Model):
Vendor_Name = models.CharField(max_length=255, null=True)
Region = MultiSelectField(choices=CHOICES)
Area = MultiSelectField(choices=AREACHOICES)
//api data
class invoiceapi(models.Model):
Vendor_Name = models.CharField(max_length=155, null=True)
area = models.CharField(max_length=155, null=True)
country = models.CharField(max_length=155, null=True)
views.py:
def homeview(request):
userb = Userbase.objects.all()
table_data= requests.get('http://127.0.0.1:1500/api/').json()
if request.method == 'POST':
userb = Userbase()
userb.Area = request.POST.getlist('Area')
userb.country = request.POST.getlist('country')
userb.Vendor_Name = request.POST.get('Vendor_Name')
userb.save()
# api data saving in db
for new_data in table_data:
data = {
'area': new_data['area'],
'country': new_data['country'],
'VendorName': new_data['VendorName'],
}
user = invoiceapi.objects.create(**data)
user.save()
//search filter
if request.method == 'POST':
finder = request.POST['Vendor_Name']
invoiceuser = invoiceapi.objects.filter(PBK_Desc__iexact=finder)
print(invoiceuser)
print(finder)
return render(request, 'home.html',
{'userb':userb,'table_data':table_data,'finder':finder})
return render(request, 'home.html', {'userb':userb,'table_data':table_data})
html:
<form action=" " method="POST" autocomplete="off">
{% csrf_token %}
<div class="row">
<div class="row" id="row_id">
<br>
<div style="margin-left: 19px; font-size: 17px;">Payment Term</div>
<div class="row" id="id_row">
<input type="text" name="Vendor_Name" maxlength="255" class="form-control mb-3"
style="margin-left: 30px; " placeholder="Vendor_Name" id="Vendor_Name" required=""">
</div>
<br>
<br>
<input type="submit" value="Apply" id="btn_submit" style=" width:90px; height:45px; margin-left: 40px; margin-bottom: 30px;"
class="btn btn-success btn" >
<input type="reset" value="Reset" id="btn_submit" style=" width:90px; height:45px;margin-left: 65px; margin-bottom: 30px;"
class="btn btn-success btn">
</div>
</form>
</div>
</div>
<div class='container-l' id='table-wrapper' style="height:330px;width:100.5%; ">
<div id='container-table'style="height: 1050px;">
{% if userb %}
<table class="table table-striped border datatable" id='table_id'>
<thead>
<thead id="tablehead">
<tr>
<th> Area </th>
<th> Country </th>
<th> VendorName </th>
</tr>
</thead>
<tbody>
{% for list in table_data %}
<tr>
<td>{{list.area}}</td>
<td>{{list.country}}</td>
<td>{{finder}}</td>
</tr>
{% endfor %}
</tbody>
</table>
</body>
</div>
{% endif %}

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__'

Django - Deleting using modal: show and delete only the first item from the table

Please help me understand the problem. I try to use the modal to delete each line separately but instead of displaying and deleting my actual line, it always displays and deletes the first line in the table. Where am I wrong with the code? Below my settings. Thank you very much.
models.py
class Post(models.Model):
class DisplayOnlyPublicat(models.Manager):
def get_queryset(self):
return super().get_queryset() .filter(status='publicat')
options =(
('draft', 'nepublicat'),
('publicat', 'publicat')
)
title = models.CharField(max_length=250)
poster = models.ImageField ( upload_to ='posts/', default='posts/poster_articole_pp.jpg')
category = models.ForeignKey(Category, on_delete=models.SET_DEFAULT, default=1)
slug = models.SlugField(max_length=250, unique_for_date='publish')
publish = models.DateTimeField(default=timezone.now)
author = models.ForeignKey (User, null=True, on_delete=models.SET_NULL, related_name='profipedia_posts')
short_content = models.TextField(null=True)
# content = models.TextField()
# content = RichTextField()
content = RichTextUploadingField(external_plugin_resources=[( 'emojione', '/static/vendor/ckeditor_plugins/emojione/' , 'plugin.js', )],)
status = models.CharField(max_length=10, choices=options, default='draft')
id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False)
objects = models.Manager() #denumire initiala
dop = DisplayOnlyPublicat() # denumire custom
def get_absolute_url(self):
return reverse('posts:articol', args=[self.slug])
# sa deschida articolul pe baza de denumire(slug) din sectiunea admin indiferent de statusul articolului (publicat/nepublicat)
# def get_absolute_url_adm(self):
# return reverse('posts:articolAdm', args=[self.slug])
class Meta:
ordering = ('-publish',)
def __str__(self):
return self.title
views.py
def delete_articol(request, articol_id):
post = Post.objects.get(pk=articol_id)
post.delete()
messages.success(request, "Articolul a fost sters!")
return redirect('posts:articoleAdm')
urls.py
urlpatterns = [
path('', views.articole, name='articole'),
path('articole-admin/', views.articoleAdm, name='articoleAdm'),
path('<slug:post>/', views.articol, name='articol'),
path('articole-admin/creare-articol/', views.creareArticol, name='creareArticol'),
path('articole-admin/<pk>/', views.articolAdm, name='articolAdm'),
path('modificare-articol/<str:pk>/', views.modificareArticol, name='modificareArticol'),
path('sterge-articol/<articol_id>/', views.delete_articol, name='stergeArticol'),
path('filtru/<category>', views.CatListView.as_view(), name='categorieArticol'),
]
html template
<table class="data-table data-table-pagination data-table-standard responsive nowrap hover"
id="datatableHover" data-order='[[ 0, "desc" ]]'>
<thead>
<tr>
<th class="text-muted text-small text-uppercase">Poster</th>
<th class="text-muted text-small text-uppercase">Autor</th>
<th class="text-muted text-small text-uppercase">Titlu</th>
<th class="text-muted text-small text-uppercase">Status</th>
<th class="text-muted text-small text-uppercase">Categorie</th>
<th class="text-muted text-small text-uppercase">Data</th>
<th class="empty"> </th>
<th class="empty"> </th>
<th class="empty"> </th>
</tr>
</thead>
<tbody>
{% for post in posts %}
<tr>
<td class="p-1"><img width="100" height="100%" class="rounded" src="{{post.poster.url}}"
alt=""></td>
<td>{{post.author}}</td>
<td><a class="list-item-heading body" href="{{post.id}}">{{post.title}}</a></td>
{% if post.status == "draft" %}
<td><span class="badge rounded-pill bg-muted">{{post.status}}</span></td>
{% else %}
<td><span class="badge bg-outline-success">{{post.status}}</span></td>
{% endif %}
{% if post.category.name == "nealocata" %}
<td><span class="badge rounded-pill bg-muted">{{ post.category }}</span></td>
{% else %}
<td><span class="badge bg-outline-muted">{{ post.category }}</span></td>
{% endif %}
<td> <small>{{post.publish|date:"d.m.Y - H:m:s"}}</small></td>
<td> <button class="btn btn-icon btn-icon-only btn-foreground-alternate edit-datatable " data-bs-toggle="tooltip" data-bs-placement="top" title="modificare articol" type="button" data-bs-delay="0"><i data-acorn-icon="eye"></i></button></td>
<td> <button class="btn btn-icon btn-icon-only btn-foreground-alternate edit-datatable " data-bs-toggle="tooltip" data-bs-placement="top" title="modificare articol" type="button" data-bs-delay="0"><i data-acorn-icon="edit"></i></button></td>
<td><button type="button" class="btn btn-icon btn-icon-only btn-foreground-alternate" data-bs-toggle="modal" data-bs-target="#deletePostPPP"><i data-acorn-icon="bin"></i></button></td>
</tr>
<!-- delete modal-->
<div class="modal fade" id="deletePostPPP" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Modal title</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal"
aria-label="Close"></button>
</div>
<div class="modal-body">Sigur vrei să ștergi articolul <br>
<strong>"{{post.title}}"</strong>?</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary"
data-bs-dismiss="modal">Close</button>
<a href="{% url 'posts:stergeArticol' post.id %}"><button type="submit"
class="btn btn-primary">Understood</button></a>
</div>
</div>
</div>
</div>
{% endfor %}
</tbody>
</table>
Your delete buttons all refer to the same modal. The issue is that all the modals you generate have the same id. When referring to that id, the first modal will be shown.
What you should do instead is give each modal a separate id, containing e.g. the post id. Then call that specific modal in your delete button.
Your delete button:
<td><button type="button" class="btn btn-icon btn-icon-only btn-foreground-alternate" data-bs-toggle="modal" data-bs-target="#deletePostPPP-{{post.id}}"><i data-acorn-icon="bin"></i></button></td>
Your modal:
<!-- delete modal -->
<div class="modal fade" id="deletePostPPP-{{post.id}}" tabindex="-1" role="dialog" aria-hidden="true">

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()

how to take input from one page and send them into another page in django

I'm fairly new at this. I'm trying to build a report page in iframe according to user requirement user can create report with src, width and height ...and i successfully done this...i am able to create the report now i want this created report name will be show in the dropdown menu and when the user click on report name then user can see the report and the name of the report will add on dynamically in the dropdown....
i'm waiting for response ..here i'm going to share the code what i have done ...
i would say one more thing i don't want to add these data (Src,width ,height,name of the report) in the data base ...is that possible to create report and get the same report when i will click on the report name.
index.html
<li class="dropdown">
Reports<span class="caret"></span>
<ul class="dropdown-menu">
<li class="dropdown-header">Reports</li>
<li>
<div class="buttons pull-right">
<i class="fa fa-plus"></i>
</div>
Report one
</li>
{% for item in report_item %}
<li>
{{item.name}}
</li>
{% endfor %}
</ul>
</li>
reportform.html
<form action = "add" method= "post" enctype="multipart/form-data" class="form form-horizontal">
{% csrf_token %}
<div class="panel panel-default">
<div class="panel-heading">
<strong>Add Report</strong>
</div>
<div class="panel-body">
<table class="table table-hover report-body attr-table">
<tr>
<td>URL</td>
<td>
<input type="text" name="src">
</td>
</tr>
<tr>
<td>WIDTH</td>
<td>
<input type="number" name="width">
</td>
</tr>
<tr>
<td> HEIGHT</td>
<td>
<input type="number" name="height">
</td>
</tr>
<tr>
<td> NAME OF THE REPORT</td>
<td>
<input type="text" name="name">
</td>
</tr>
</table>
<input type="submit">
</div>
</div>
</form>
report_one.html
<iframe src = {{src}} width= {{width}} height= {{height}} frameborder="0" allowfullscreen allowtransparency ></iframe>
**view.py **
def reportone(request):
return render(request, 'report_one.html')
def reporttwo(request):
return render(request, 'report_two.html')
def reporttest(request):
return render(request, 'reportform.html')
def add(request):
if request.method == "POST":
report_item={}
src=request.POST['src']
width=request.POST['width']
height=request.POST['height']
name=request.POST['name']
report_item={'src':src, 'width':width, 'height':height, 'name':name}
return render(request, 'report_one.html', report_item)
else:
return render(request, 'report_one.html' , report_item)
urls.py
from django.contrib import admin
from django.urls import path
from extras.views import ObjectChangeLogView
from . import views
app_name = 'report'
urlpatterns = [
path('reportone', views.reportone, name='reportone'),
path('reporttwo', views.reporttwo, name='reporttwo'),
path('reporttest', views.reporttest, name='reporttest'),
path('add', views.add, name='add'),
]
Please try this:
models.py
from django.db import models
class Report(models.Model):
url = models.URLField(null=False,max_length=300)
width = models.IntegerField(default=300)
height = models.IntegerField(default=200)
name = models.CharField(max_length = 50)
forms.py
from .models import Report
from django.db import models
class ReportForm(forms.Form):
width = forms.CharField(widget=forms.NumberInput(attrs={'class':' form-control'}))
height = forms.CharField(widget=forms.NumberInput(attrs={'class':' form-control'}))
url = forms.URLField(max_length=300)
name = forms.CharField(max_length = 50)
class Meta:
model = Report
fields = [ "url","width","height","name"]
views.py
from .forms import ReportForm
from .models import Report
def reporttest(request):
form = ReportForm()
return render(request, 'reportform.html',{'form':form})
def add(request):
report_item={}
if request.method == "POST":
obj= Report()
obj.url =request.POST['url']
obj.width=request.POST['width']
obj.height=request.POST['height']
obj.name=request.POST['name']
obj.save()
report_item={'src':request.POST['url'], 'width':request.POST['width'], 'height':request.POST['height'], 'name':request.POST['name']}
return render(request, 'report_one.html', report_item)
else:
return render(request, 'report_one.html' , report_item)
reportform.html
<form action = "add" method= "post" enctype="multipart/form-data" class="form form-horizontal">
<div class="panel panel-default">
<div class="panel-heading">
<strong>Add Report</strong>
</div>
<div class="panel-body">
<table class="table table-hover report-body attr-table">
{% csrf_token %}
{% for field in form.visible_fields %}
<tr>
<td>{{field.label}}</td>
<td>{{field}}</td>
</tr>
{% endfor %}
</table>
<input type="submit" >
</div>
</div>
</form>
report_one.html
<iframe width="{{width}}" height="{{height}}" src="{{src}}" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
please try this.After change model then migrate it.
simple url for checking :https://www.youtube.com/embed/F5mRW0jo-U4

Taking Attendance in Django Python

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.