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

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

Related

Field 'id' expected a number but got 'product_id' django [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
In my ecommerce app when I click on add to cart the product goes to the cart but when I click on the cart it gives me the error that 'Field 'id' expected a number but got 'product_id''. Basically I use context_processor to pass the cart.py information to the template.
Link to the cart from base.html is:
<div class="navbar-item">
Cart {% if cart %}({{cart|length}}){% endif %}
</div>
When I click on cart this error is generated:
Field 'id' expected a number but got 'product_id'
my project/urls.py is
path('cart/',include("cart.urls")),
my cart/urls.py is
urlpatterns = [
path('',views.cart_detail, name='cart')
]
my cart/cart.py is
from django.conf import settings
from product.models import Product
class Cart(object):
def __init__(self, request):
self.session = request.session
cart = self.session.get(settings.CART_SESSION_ID)
if not cart:
cart = self.session[settings.CART_SESSION_ID] = {}
self.cart = cart
def __iter__(self):
for p in self.cart.keys():
self.cart[(p)]['product'] = Product.objects.get(pk=p)
for item in self.cart.values():
item['total_price'] = item['product'].price * item['quantity']
yield item
def __len__(self):
return sum(item['quantity'] for item in self.cart.values())
def add(self, product_id, quantity=1, update_quantity=False):
product_id = str(product_id)
if product_id not in self.cart:
self.cart[product_id] = {'quantity': 1, 'id': product_id}
if update_quantity:
self.cart[product_id]['quantity'] += int(quantity)
if self.cart[product_id]['quantity'] == 0:
self.remove(product_id)
self.save()
print(self.cart)
def remove(self, product_id):
if product_id in self.cart:
del self.cart[product_id]
self.save()
def save(self):
self.session[settings.CART_SESSION_ID] = self.cart
self.session.modified = True
def clear(self):
del self.session[settings.CART_SESSION_ID]
self.session.modified = True
def get_total_cost(self):
for p in self.cart.keys():
self.cart[str(p)]['product'] = Product.objects.get(pk=p)
return sum(item['quantity'] * item['product'].price for item in self.cart.values())
my context_processors.py is
def cart(request):
return {'cart': Cart(request)}
and my cart.html is:
{% extends 'core/base.html' %}
{% block title %}Cart | {% endblock %}
{% block content %}
<h1 class="title">Cart</h1>
{% if cart %}
<div class="box mb-6">
<div class="table">
<table class="table is-fullwidth is-striped">
<thead>
<th></th>
<th>Product</th>
<th>Quantity</th>
<th>Price</th>
<th></th>
</thead>
<tbody>
{% for item in cart %}
<tr>
<td>
<figure class="image is-64x64">
<img src="{{ item.product.get_thumbnail }}">
</figure>
</td>
<td>
{{ item.product.title }}
</td>
<td>
{{ item.quantity }}
-
+
</td>
<td>${{ item.total_price }}</td>
<td>Remove</td>
</tr>
{% endfor %}
</tbody>
<tfoot>
<tr>
<td></td>
<td><strong>Total cost</strong></td>
<td><strong>{{ cart|length}}</strong></td>
<td colspan="2"><strong>${{ cart.get_total_cost }}</strong></td>
</tr>
</tfoot>
</table>
</div>
</div>
<h2 class="subtitle">Contact information</h2>
<form method="post" action="." id="payment-form">
{% csrf_token %}
{% if form.non_field_errors %}
<div class="notification is-danger">
{{ form.non_field_errors}}
</div>
{% endif %}
{% if form.errors %}
<div class="notification is-danger">
<ul>
{% for field in form %}
{% for error in field.errors %}
<li><strong>{{ field.label }}: </strong>{{ error }}</li>
{% endfor %}
{% endfor %}
</ul>
</div>
{% endif %}
<div class="columns">
<div class="column is-6">
<div class="field">
<label>First name</label>
<div class="control">
<input class="input" type="text" name="first_name">
</div>
</div>
<div class="field">
<label>Last name</label>
<div class="control">
<input class="input" type="text" name="last_name">
</div>
</div>
<div class="field">
<label>E-mail</label>
<div class="control">
<input class="input" type="email" name="email">
</div>
</div>
<div class="field">
<label>Phone</label>
<div class="control">
<input class="input" type="text" name="phone">
</div>
</div>
</div>
<div class="column is-6">
<div class="field">
<label>Address</label>
<div class="control">
<input class="input" type="text" name="address">
</div>
</div>
<div class="field">
<label>Zip code</label>
<div class="control">
<input class="input" type="text" name="zipcode">
</div>
</div>
<div class="field">
<label>Place</label>
<div class="control">
<input class="input" type="text" name="place">
</div>
</div>
</div>
</div>
</form>
<h2 class="subtitle">Payment information</h2>
<div id="card-element">
<!-- A Stripe Element will be inserted here -->
</div>
{% if messages %}
{% for message in messages %}
<div class="notification is-danger">{{ message }}</div>
{% endfor %}
{% endif %}
<div class="field">
<div class="control">
<button class="button is-dark mt-4 is-uppercase">Checkout</button>
</div>
</div>
</div>
{% else %}
<p>You don't have any products in your cart!</p>
{% endif %}
{% endblock %}
Aren't you casting the product_id to a string with str(product_id) ? And later you're passing it as an number but it's still an string. In cart.py and function add
The answer is I did not clear cookies. As I clear those o the code
change this:
{'quantity': 1, 'id': product_id}
with this
{'quantity': 1, 'id': int(product_id)}

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>

unable to update the fields in model Django

I am trying to edit user details of a specific user when admin logins its going to edit page but when I press the update button it's not updating not showing any error message. (correct me please if I am wrong).
This is my edit.html
{% extends 'base.html' %}
{% block title %}edit details{% endblock %}
{% block content %}
{% if emp %}
<form method="POST" class="form-inline my-2 my-lg-0" ">
{% csrf_token %}
<div class="container">
<br>
<div class="form-group row">
<label class="col-sm-1 col-form-label"></label>
<div class="col-sm-4">
<h3>Update Details</h3>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Employee User:</label>
<div class="col-sm-4">
<input type="text" id="id_user" required maxlength="20" value="{{
emp.user }}"/>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Employee first_name:</label>
<div class="col-sm-4">
<input type="search" id="id_first_name" required maxlength="100"
value="{{ emp.first_name }}" />
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Employee last_name:</label>
<div class="col-sm-4">
<input type="text" id="id_last_name" required maxlength="100" value="{{
emp.last_name }}" />
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Employee Email:</label>
<div class="col-sm-4">
<input type="email" id="id_email" required maxlength="254" value="{{
emp.email }}" />
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Employee Gender:</label>
<div class="col-sm-4">
<input type="text" id="id_gender" required maxlength="15" value="{{
emp.gender }}" />
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Employee Age:</label>
<div class="col-sm-4">
<input type="text" id="id_age" required maxlength="100" value="{{
emp.age }}" />
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Employee salary:</label>
<div class="col-sm-4">
<input type="text" name="ename" id="id_salary" required maxlength="100"
value="{{ emp.salary }}" />
</div>
</div>
<div class="form-group row">
<label class="col-sm-1 col-form-label"></label>
<div class="col-sm-4">
<button type="submit" class="btn btn-success">Update</button>
</div>
</div>
</div>
</form>
{% endif %}
{% endblock %}
This is my profile.html page
{% if user.is_authenticated %}
{% if user.is_superuser %}
<table class="table table-striped table-bordered table-sm">
<thead class="thead-dark">
<tr>
<th>Employee User</th>
<th>Employee first_name</th>
<th>Employee last_name</th>
<th>Employee Email</th>
<th>Employee Gender</th>
<th>Employee Age</th>
<th>Employee Salary</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{% for employee in employees %}
<tr>
<td>{{ employee.user }}</td>
<td>{{ employee.first_name }}</td>
<td>{{ employee.last_name }}</td>
<td>{{ employee.email }}</td>
<td>{{ employee.gender }}</td>
<td>{{ employee.age }}</td>
<td>{{ employee.salary }}</td>
<td>
<a href="{% url 'edit' employee.id %}"><span class="glyphicon
glyphicon-pencil" >Edit</span></a>
Delete
</td>
</tr>
{% endfor %}
</tbody>
</table>
<br>
<br>
<center><a href="{% url 'signup' %}" class="btn btn-primary">Add New
Record</a></center>
{% else %}
<p>username : {{ user }}</p>
<p>firstname : {{ user.first_name }}</p>
<p>lastname : {{ user.last_name }}</p>
<p>{{user.employee.age}}</p>
<p>
Edit details
</p>
<p>
Change password
</p>
{% endif %}
{% endif %}
This is view.py of edit method
def edit(request, emp_id):
if request.method == 'POST':
emp = employee.objects.get(pk=emp_id)
form = EmployeForm(request.POST or None, instance=emp)
if form.is_valid():
form.save()
messages.success(request, ('Item has been edited'))
return HttpResponseRedirect('view_profile')
else:
emp = employee.objects.get(pk=emp_id)
return render(request, 'edit.html', {'emp': emp})
def view_profile(request):
employees = employee.objects.all()
args= {'user':request.user,'employees':employees}
return render(request,'profile.html',args)
This is my model page
class employee(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
email = models.EmailField(max_length=50)
gender = models.CharField(max_length=1,choices=(('M','Male'),
('F','Female')),blank=True)
age = models.PositiveIntegerField(blank=True, null=True)
salary = models.CharField(blank = True,max_length=50
def __str__(self):
return self.user.username
Please, any advice on how to troubleshoot or any documentation I can read.
You're not using the form properly. Forms are not only for validation, they are also responsible for rendering the error messages. You want to change your view to pass the form to the template:
def edit(request, emp_id):
emp = employee.objects.get(pk=emp_id)
if request.method == 'POST':
form = EmployeForm(request.POST, instance=emp)
if form.is_valid():
form.save()
messages.success(request, ('Item has been edited'))
# this one is probably not going to work
# as expected - you may want to check the
# doc for the `redirect` shortcut instead
return HttpResponseRedirect('view_profile')
else:
form = EmployeForm(instance=emp)
return render(request, 'edit.html', {'emp': emp, 'form':form})
Then in your template instead of manually writing the whole form markup, use the form for rendering so you have the validation errors correctly displayed.

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.

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