django put save button - python

I would like to change the data that is in this column from a form but I can't display the data and save them and also add a delete button. anyone have a solution.
models.py
class Employe(models.Model):
Matricule = models.CharField(max_length=10, null=False)
Prenom = models.CharField(max_length=40, null=True)
Nom = models.CharField(max_length=40, null=True)
Tel = models.CharField(max_length=20, null=True)
Adresse = models.CharField(max_length=100, null=True)
Courriel = models.CharField(max_length=100, null=True)
Horaire = models.CharField(max_length=50, null=True)
Date_embauche = models.CharField(max_length=100, null=True)
UtilisateurOSP = models.CharField(max_length=100, null=True)
MotdepasseOSP = models.CharField(max_length=50, null=True)
Anciennete = models.CharField(max_length=10, null=True)
data_created = models.DateTimeField(auto_now_add=True, null=True)
class Disciplinaire(models.Model):
employe = models.ForeignKey(Employe, null=True, on_delete=models.SET_NULL)
Avis_verbal = models.CharField(max_length=300, null=True)
Avis_ecrit = models.CharField(max_length=300, null=True)
Avis_ecrit2 = models.CharField(max_length=300, null=True)
Suspension = models.CharField(max_length=300, null=True)
Fin_emploie = models.CharField(max_length=300, null=True)
data_created = models.DateTimeField(auto_now_add=True, null=True)
forms.py
class disciplinaireForm(ModelForm):
class Meta:
model = Disciplinaire
fields = '__all__'
views.py
def updateDisciplinaire(request, id):
emp = Disciplinaire.filter()
forms = disciplinaireForm(instance=emp)
if request.method == 'POST':
forms = disciplinaireForm(request.POST, instance=emp)
if forms.is_valid():
forms.save()
return redirect('/')
context = {'forms':forms}
return render(request, 'accounts/updateDisciplinaire.html', context)
page.html
<th scope="col">Avis Verbal</th>
<th scope="col">1er Avis Écrit</th>
<th scope="col">2e Avis Écrit</th>
<th scope="col">Suspension</th>
<th scope="col">Fin d'emploi</th>
<th scope="col">Action</th>
</tr>
{% for j in disci %}
<tr>
<td>{{j.Avis_verbal}}</td>
<td>{{j.Avis_ecrit}}</td>
<td>{{j.Avis_ecrit2}}</td>
<td>{{j.Suspension}}</td>
<td>{{j.Fin_emploie}}</td>
<td><a class="btn btn-outline-info" href="{% url 'updateDisciplinaire' j.id %}">Modifier</a>
</tr>
{% endfor %}
data and button
error message

The error says that in line 102 from your views.py you are trying to filter something. If you want to filter try:
emp_all = Disciplinaire.objects.filter(employe = id)
for emp in emp_all:
print(emp.Matricule)
you need to put how to filter, by which field.
When you use filter it will get you a queryset, a list of records not just one single record, if you want a single record you can use get:
emp = Disciplinaire.objects.get(employe = id)

Related

Reverse query in Django Many to Many

I have a problem in django reverse many to many. Basically, I think I am missing something that I couldn't understand properly yet.
I have these models and views.
models.py
class TheorySyllabus(models.Model):
name = models.CharField(max_length=100, null=True, blank=True)
subject_duration = models.ManyToManyField(
SubjectDuration, related_name='subject_durations')
course_type = models.ForeignKey(
CourseType, on_delete=models.DO_NOTHING, null=True, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.name
class Meta:
verbose_name_plural = 'Theory Syllabus'
class TheoryCourse(models.Model):
name = models.CharField(max_length=100)
student = models.ManyToManyField(Student, related_name='theory_courses')
theory_syllabus = models.ForeignKey(
TheorySyllabus, on_delete=models.DO_NOTHING, null=True, blank=True)
is_active = models.BooleanField(default=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.name
class Student(models.Model):
user = models.OneToOneField(CustomUser, on_delete=models.CASCADE)
first_name = models.CharField(max_length=200)
last_name = models.CharField(max_length=200)
date_of_birth = models.DateField()
fiscal_code = models.CharField(max_length=50)
phone = models.CharField(max_length=50)
license = models.ForeignKey(
License, on_delete=models.PROTECT, blank=True, null=True)
picture = models.ImageField(
blank=True, null=True, default='default.png')
id_card = models.ForeignKey(
IDCard, on_delete=models.PROTECT, blank=True, null=True)
address = models.CharField(max_length=100)
cap = models.CharField(max_length=10)
city = models.CharField(max_length=100)
province = models.CharField(max_length=100)
country = models.CharField(max_length=100)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
is_active = models.BooleanField(default=True)
def __str__(self):
return self.user.first_name + ' ' + self.user.last_name
views.py
class CourseListView(ListView):
model = TheoryCourse
queryset = TheoryCourse.objects.filter(
is_active=True).order_by('-created_at')
template_name = 'theory/course_list.html'
context_object_name = 'theory_courses'
paginate_by = 10
template
<div class="card-body table-responsive p-0">
<table class="table table-hover text-nowrap table-bordered">
<thead>
<tr>
<th>Course Type</th>
<th>Course Name</th>
</tr>
</thead>
<tbody>
{% for course in theory_courses %}
<tr>
<td>{{course.theory_syllabus.name}}</td>
<td>{{course.name}}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
What I need to do, is to retrieve the total number of students that are in each TheoryCourse model. But I really have no idea how to use the reverse relationship.
I tried to use that in the template with something like:
{% for student in theory_courses.students.all %}
{% endfor %}
But, it's not working. I read all the django documentation but either I didn't understand something or I am doing something wrong.
Any help would be appreciated
So, you have student in your model, not students. Thus for will look something like this
{% for student in theory_courses.student.all %}
{% endfor%}
Furthermore, if you want to get only count, you can just use
{% for student_count in theory_courses.student.count %}
{% endfor %}
P.S. That has nothing to do with reverse (related_name) in many to many. related name just means that you can access your TheoryCourse model from Student with Student.theory_courses

Why is my django template tag not able to iterate my object across a model

I'm having an issue getting my template to produce a table that includes the models name, a count of the number of child models to that parent, and then a sum of a field in that child model. I've gotten the first two to return the desired output, but the last two only yield an empty space in the cell. Can't figure out where I'm missing it.
MODELS.PY FILE
class Employee(models.Model):
user = models.OneToOneField(User,null=True, blank=True, on_delete=models.CASCADE)
username = models.CharField(max_length=200, null=True)
firstname = models.CharField(max_length=200, null=True)
lastname = models.CharField(max_length=200, null=True)
email = models.CharField(max_length=200, null=True)
team = models.ForeignKey(Team, null=True, on_delete=models.SET_NULL)
profile_pic = models.ImageField(default="hulkhoganicon.jpg", null=True, blank=True)
date_created = models.DateTimeField(auto_now_add=True, null=True)
def __str__(self):
return self.firstname
class Event(models.Model):
STATUS = (
('Appointment Set', 'Appointment Set'),
('Hot Lead', 'Hot Lead'),
('Booked', 'Booked'),
('Lost Sale', 'Lost Sale'),
('X-Dated', 'X-Dated'),
)
PACKAGE = (
('1st Package', '1st Package'),
('2nd Package', '2nd Package'),
('3rd Package', '3rd Package'),
('4th Package', '4th Package'),
)
ADDONS = (
('None','None'),
('2nd Setup', '2nd Setup'),
('Uplighting', 'Uplighting'),
('Monogram', 'Monogram'),
('Intelligent Lighting', 'Intelligent Lighting'),
('Other', 'Other'),
)
employee = models.ForeignKey(Employee, null=True, on_delete=models.SET_NULL)
eventType = models.ForeignKey(EventType, null=True, on_delete=models.SET_NULL)
teamAssigned = models.ForeignKey(Team, null=True, on_delete=models.SET_NULL)
eventName = models.CharField(max_length=1000, null=True)
date_of_event = models.DateField(auto_now=False, null=True)
date_of_appt = models.DateField(auto_now=False, null=True)
date_booked = models.DateField(auto_now=False, null=True)
date_created = models.DateTimeField(auto_now_add=True, null=True)
package = models.CharField(max_length=200, null=True, choices=PACKAGE)
price = models.FloatField(null=True)
addons = models.CharField(max_length=200, null=True, choices=ADDONS)
addonPrice = models.FloatField(null=True)
addonOverage = models.FloatField(null=True)
status = models.CharField(max_length=200, null=True, choices=STATUS)
notes = models.CharField(max_length=1000, null=True)
tags = models.ManyToManyField(Tag)
def __str__(self):
return self.eventName
VIEWS.PY FILE
def teamDashboard(request):
events = Event.objects.all()
employees = Employee.objects.all()
total_employees = employees.count()
total_events = events.count()
events_sum = events.aggregate(Sum('price'))['price__sum']
booked_sum = events.filter(status='Booked').aggregate(Sum('price'))['price__sum']
Green_events = events.filter(teamAssigned__name='Green').count()
Green_events_sum = events.filter(teamAssigned__name='Green').aggregate(Sum('price'))['price__sum']
Green_booked_sum = events.filter(teamAssigned__name='Green', status='Booked').aggregate(Sum('price'))['price__sum']
Blue_events = events.filter(teamAssigned__name='Blue').count()
Blue_events_sum = events.filter(teamAssigned__name='Blue').aggregate(Sum('price'))['price__sum']
Orange_events = events.filter(teamAssigned__name='Orange').count()
Orange_events_sum = events.filter(teamAssigned__name='Orange').aggregate(Sum('price'))['price__sum']
Purple_events = events.filter(teamAssigned__name='Purple').count()
Purple_events_sum = events.filter(teamAssigned__name='Purple').aggregate(Sum('price'))['price__sum']
Booked = events.filter(status='Booked').count()
Appointment_Set = events.filter(status='Appointment Set').count()
Appt_set_sum = events.filter(status='Appointment Set').aggregate(Sum('price'))
Date = datetime.now()
context = {'Date':Date, 'total_employees':total_employees, 'events':events, 'employees':employees,
'total_events':total_events, 'Booked':Booked, 'Appointment_Set':Appointment_Set,
'Appt_set_sum':Appt_set_sum, 'Green_events':Green_events, 'Blue_events':Blue_events,
'Orange_events':Orange_events,'Purple_events':Purple_events, 'Green_events_sum':Green_events_sum,
'Blue_events_sum':Blue_events_sum, 'Orange_events_sum':Orange_events_sum,
'Purple_events_sum':Purple_events_sum,'Green_booked_sum':Green_booked_sum, 'events_sum':events_sum,
'booked_sum':booked_sum,
}
context['segment'] = 'teamDashboard'
return render(request, 'accounts/team-dashboard.html', context)
TEAM-DASHBOARD.HTML FILE
<tbody>
{% for employee in employees %}
{% if employee.team.name == "Green" %}
<tr>
<td></td>
<td>{{employee.firstname}}</td>
<td>{{employee.event_set.count}}</td>
<td>{{events_sum.employee_set}}</td>
<td>{{employee.events.booked_sum}}</td>
</tr>
{% endif %}
</tbody>
{% endfor %}
I'm just starting out with Django so thank you in advance if I'm making a really dumb mistake!

'Order' object is not iterable [Django]

At the very beginning I would note that I'm a beginner as hel :P I have two models in my django models.py and I want them to display on a page. The issue is that I got error about no possible iteration and I don't know why.
Also, I'm following the Crash Course from Youtube with changing some thing for my use :)
Could You please advice as I haven't found any useful tips on google?
Thanks!
models.py
from django.db import models
# Create your models here.
class Supplier(models.Model):
name = models.CharField(max_length=200, null=True)
phone = models.CharField(max_length=200, null=True)
email = models.CharField(max_length=200, null=True)
date_created = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.name
class Order(models.Model):
STATUS = (
('Pending Order', 'Pending Order'),
('Pending PR', 'Pending PR'),
('Declined by SME', 'Declined by SME'),
('Declined by Finance', 'Declined by Finance'),
('Ordered', 'Ordered'),
('Canceled', 'Canceled'),
('Delivered', 'Delivered'),
)
product = models.CharField(max_length=200, null=True)
link = models.CharField(max_length=400, null=True)
supplier = models.ForeignKey(Supplier, null=True, on_delete=models.SET_NULL)
date_created = models.DateTimeField(auto_now_add=True, null=True)
status = models.CharField(max_length=200, null=True, default='Pending Order', choices=STATUS)
amount = models.CharField(max_length=40, null=True)
comment = models.CharField(max_length=400, null=True, blank=True)
requester = models.CharField(max_length=40, null=True)
def __str__(self):
return self.product
views.py
from django.shortcuts import render
from .models import *
# Create your views here.
def home(request):
return render(request, 'accounts/dashboard.html')
def products(request):
return render(request, 'accounts/products.html')
def customer(request):
return render(request, 'accounts/customer.html')
def orders(request):
orders = Order.objects.all()
customers = Supplier.objects.all()
context = {'orders': orders, 'customers': customers}
return render(request, 'accounts/orders.html', {'orders': Order})
And a part of my HTML which is only bootstrap and HTML
<table class="table table-sm">
<tr>
<th>Supplier</th>
<th>Product (Name)</th>
<th>Product (ID)</th>
<th>Date Orderd</th>
<th>Status</th>
<th>Requester</th>
<th>Update</th>
<th>Remove</th>
</tr>
{% for order in orders %}
<tr>
<td>{{order.supplier}}</td>
<td>{{order.product}}</td>
<td>{{order.link}}</td>
<td>{{order.date_created}}</td>
<td>{{order.status}}</td>
<td>{{order.requester}}</td>
{% endfor %}
</table>
def orders(request):
orders = Order.objects.all()
customers = Supplier.objects.all()
context = {'orders': orders, 'customers': customers}
return render(request, 'accounts/orders.html', context)
Try this.
In render you're passing the Order class instead of your queryset orders

Django {% for loop - showing 1 out of 3 values

I added for loop to my html, after I added more data to the Queryset. For some reason it's showing 1 out of 3 values I passed. - I could print them, it's just not showing up on the html.
The result page - client_name (in blue), missing product_name + waiting_time (in red)
Any ideas? thank you
models.py
class Orders(models.Model):
created_date = models.DateTimeField(auto_now_add=True)
client_id = models.IntegerField()
client_name = models.CharField(max_length=50, blank=True, null=True)
delivery_city = models.CharField(max_length=50, blank=True, null=True)
delivery_address = models.CharField(max_length=50, blank=True, null=True)
product_id = models.IntegerField()
sold_by = models.CharField(max_length=20)
sale_type = models.CharField(max_length=20, blank=True, null=True)
units_to_buy = models.IntegerField(blank=True, null=True)
order_cost = models.DecimalField(decimal_places=2, max_digits=100000, blank=True, null=True)
payment_method = models.CharField(max_length=20, blank=True, null=True)
payment_channel = models.CharField(max_length=20, blank=True, null=True)
invoice = models.CharField(max_length=20, blank=True, null=True)
delivery_cost = models.DecimalField(decimal_places=2, max_digits=100000, blank=True, null=True)
delivery_type = models.CharField(max_length=20, blank=True, null=True)
delivery_status = models.CharField(max_length=20, default='ממתין למשלוח')
delivery_person_name = models.CharField(max_length=20, blank=True, null=True)
notes = models.TextField(blank=True, null=True)
modified_date = models.DateTimeField(auto_now=True)
def __str__(self):
return '{}'.format(self.client_name + ' - (' + self.sold_by + ')')
class Clients(models.Model):
first_name = models.CharField(max_length=20)
last_name = models.CharField(max_length=20, blank=True, null=True)
client_type = models.CharField(max_length=15, blank=True, null=True)
company_name = models.CharField(max_length=30, blank=True, null=True)
address = models.CharField(max_length=30, blank=True, null=True)
city = models.CharField(max_length=15, blank=True, null=True)
phone_number = models.CharField(max_length=10)
additional_phone_number = models.CharField(max_length=10, blank=True, null=True)
email = models.EmailField(max_length=30, blank=True, null=True)
card_type = models.CharField(max_length=15, blank=True, null=True)
four_digits = models.IntegerField(blank=True, null=True)
notes = models.TextField(blank=True, null=True)
added = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now=True)
def __str__(self):
return '{}'.format(self.first_name)
class Products(models.Model):
product_name = models.CharField(max_length=50, verbose_name=u'שם המוצר')
supplier_name = models.CharField(max_length=20, blank=True, null=True)
purchase_price = models.DecimalField(decimal_places=2, max_digits=100000, blank=True, null=True)
purchase_price_before_fees = models.DecimalField(decimal_places=2, max_digits=100000, blank=True, null=True)
final_price = models.DecimalField(decimal_places=2, max_digits=100000, blank=True, null=True)
final_price_before_fees = models.DecimalField(decimal_places=2, max_digits=100000, blank=True, null=True)
inventory_in = models.IntegerField(blank=True, null=True)
inventory_out = models.IntegerField(blank=True, null=True)
inventory_total = models.IntegerField(blank=True, null=True)
notes = models.TextField(blank=True, null=True)
created = models.DateTimeField(auto_now=True)
def __str__(self):
return '{}'.format(self.product_name)
URLs.py
...
path('orders/', views.orders_filter_view, name='orders'),
...
Views.py
def orders_filter_view(request):
qs = models.Orders.objects.all()
...
for order in qs:
client = models.Clients.objects.get(pk=order.client_id)
client_name = client.first_name
qs.client_name = client_name <<<<<<<<<<<<<<<<<<<<<<<<<<<<<
product = models.Products.objects.get(pk=order.product_id)
product_name = product.product_name
qs.product_name = product_name <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
tz_info = order.created_date.tzinfo
qs.waiting_time = order.created_date - datetime.datetime.now(tz_info) <<<<<<<<<<<<<<<<<<<<<<<
total_matches = qs.count()
context = {
'orders': qs, <<<<<<<<<<<<<<<<<<<<<<<<<<<<<
'view': 'הזמנות',
'total_matches': total_matches,
'titles': orders_titles
}
return render(request, 'adolim/orders.html', context)
Orders.html
{% for order in orders %}
<tr>
<td class="center">{{ order.client_name }}</td> <<<<<<<<<<<<<<<<<<<<<<<<
<td class="center">{{ order.product_name }}</td> <<<<<<<<<<<<<<<<<<<<<<<<
...
<td class="center">{{ order.delivery_person_name }}</td>
{% if order.delivery_status == 'סופק' %}
<td class="center green-text">{{ order.delivery_status }}</td>
{% else %}
<td class="center">{{ order.delivery_status }}</td>
{% endif %}
<td class="center yellow-text">{{ order.waiting_time }}</td> <<<<<<<<<<<<<<<<<
The result page - client_name (in blue), missing product_name + waiting_time (in red)
One thing you are doing wrong is you run query in a for loop which is a big problem instead I suggest you to create a query with joining tables, one way to do it is using select_related or another that I like is using values: main difference is select_related will return you objects with all the fields while values will return an array of dictionaries with specified fields.
More info regarding select_related https://docs.djangoproject.com/en/3.0/ref/models/querysets/#select-related
# I am not sure how your Models looks like but I assume it is One-to-Many Clients-Orders
def orders_filter_view(request):
# client, product in quotes is the foreign key field name
qs = models.Orders.objects.select_related('client', 'product').all()
...
# I am not sure what are you trying to do with dates
# But now you can easily access any data from foreign key objects without hitting DB again
for order in qs:
print(order.client.first_name)
print(order.product.product_name)
tz_info = order.created_date.tzinfo
qs.waiting_time = order.created_date - datetime.datetime.now(tz_info)

Column closingevent.id doesn't exist LINE 1: SELECT "closingevent"."id", "closingevent"."owner", "closing

I've a problem with my templates. I try to render the following template
{% if liste_column %}
<table>
<tr><th>Owner</th>
<th>RegimeID</th>
<th>ClosingeventID</th>
<th>Category</th>
<th>Transaction or Closing</th>
<th>**** Accounting Field</th>
<th>Data Source</th>
</tr>
{% for item in liste_column %}
<tr><td>{{item.owner}}</td>
<td>{{item.regimeid}}</td>
<td>{{item.closingeventid}}</td>
<td>{{item.category}}</td>
<td>{{item.transactionorclosing}}</td>
<td>{{item.****accountingfield}}</td>
<td>{{item.datasource}}</td>
</tr>
{% endfor %}
</table>
{% else %}
<p>No Data are available.</p>
{% endif %}
And get the error:
Column closingevent.id doesn't exist LINE 1: SELECT "closingevent"."id", "closingevent"."owner", "closing...
My table has no column which is called "closingevent"."id" and I even didn't try to get this. I get it for other templates too.
Can you help me? I think it could be the problem that my model doesn't have a primary key and just a foreign key.
class Closingevent(models.Model):
owner = models.CharField(max_length=800, blank=True, null=True)
regimeid = models.ForeignKey('Regime', models.DO_NOTHING,
db_column='regimeid')
closingeventid = models.FloatField()
category = models.CharField(max_length=800, blank=True, null=True)
closingevent = models.CharField(max_length=800, blank=True, null=True)
transactionorclosing = models.CharField(max_length=1, blank=True,
null=True)
****accountingfield = models.CharField(max_length=1, blank=True,
null=True)
datasource = models.CharField(max_length=800, blank=True, null=True)
debitacoountnumber = models.CharField(max_length=800, blank=True,
null=True)
debitsubitem = models.CharField(max_length=1, blank=True, null=True)
debitaccountname = models.ForeignKey('Lineitemaccounting',
models.DO_NOTHING,db_column='debitaccountname',
blank=True,null=True,related_name='daccountname2')
debitbalancesheet = models.CharField(max_length=1, blank=True, null=True)
debitprofitandlose = models.CharField(max_length=1, blank=True,
null=True)
debitreconciliation = models.CharField(max_length=1, blank=True,
null=True)
creditaccountnumber = models.CharField(max_length=1, blank=True,
null=True)
creditsubitem = models.CharField(max_length=1, blank=True, null=True)
creditaccountname = models.ForeignKey('Lineitemaccounting',
models.DO_NOTHING, db_column='creditaccountname', blank=True,
null=True,related_name='caccountname2')
creditbalancesheet = models.CharField(max_length=1, blank=True,
null=True)
creditprofitandloss = models.CharField(max_length=1, blank=True,
null=True)
creditreconciliation = models.CharField(max_length=1, blank=True,
null=True)
class Meta:
managed = False
db_table = 'closingevent'
unique_together = (('regimeid', 'closingeventid'),)

Categories