![](/img/trans.png)
[英]How to call a function from models.py with class based views in Django?
[英]How to call a function from models.py to views or template
我是 Django 和 Python 的初學者。 我正在創建一個工資單項目,其計算是使用 models.py 中的 function 完成的。 用戶必須通過模板輸入變量並保存到sql。 然后搜索員工(再次通過模板)和 output 他的工資單詳細信息。 那是我想使用計算function的時候。
來自數據庫的數據正在工作並由模板輸出。 至於計算出來的數據,根本就沒有顯示出來。
我一直在嘗試使用 function 無濟於事,我已經搜索了 3 天。 我不知道現在該做什么。
模型.py
from django.db import models
#Class in model.py acts as a table in database
class Add_Employee(models.Model):
name = models.CharField (max_length = 150, default = '', null = False)
position = models.CharField (max_length = 150, default = '', null = False)
email = models.EmailField (max_length = 150, default = '', null = False)
address = models.CharField (max_length = 500, default = '', null = False)
basic_pay = models.FloatField(default=None)
overtime_hours = models.IntegerField(default=None)
allowance = models.FloatField(default=None)
days_leave = models.IntegerField(default=None)
other_deductions = models.FloatField(default=None)
#Django admin page; the table will show the name
def __str__(self):
return '{}{}'.format(self.name, self.position, self.email, self.address)
def salary_calculation(self):
#Earnings
self.overtime_hours_pay = self.overtime_hours * 64
self.gross_income = self.basic_pay + self.overtime_hours + self.allowance
#Deductions
self.days_leave = self.days_leave * 512
self.pagibig = self.basic_pay * 0.01
self.gsis = self.basic_pay * 0.09
self.withholdingtax = self.basic_pay * 0.15
self.philhealth = self.basic_pay * 0.0275 / 2
self.total_deductions = self.days_leave + self.pagibig + self.gsis + self.withholdingtax + self.philhealth
#Net Pay
self.net_pay = self.gross_income - self.total_deductions
print ("Calculated.") #this was never outputted from all the times i tried.
return (self)
視圖.py
#Code for form submission and redirect back to employer page again
def add_employee_form_submit(request):
print ("Form is successfully submitted.") #print can only be seen on the terminal, not the browser
#create local variable for each variable entered using the form
name = request.POST["name"]
address = request.POST["address"]
email = request.POST["email"]
position = request.POST["position"]
basic_pay = request.POST["basic_pay"]
overtime_hours = request.POST["overtime_hours"]
allowance = request.POST["allowance"]
days_leave = request.POST["days_leave"]
other_deductions = request.POST["other_deductions"]
#assigning the local variable into the database fields
employee_info = Add_Employee(name = name, address = address, email = email, position = position, basic_pay = basic_pay, overtime_hours = overtime_hours, allowance = allowance, days_leave = days_leave, other_deductions = other_deductions )
#save the entire stuff
employee_info.save()
return render(request, 'employer.html')
def search_employee_form_submit(request):
if request.method == "POST":
search_id = request.POST['search_id']
if search_id:
employee_match = Add_Employee.objects.filter( pk = search_id ) #pk is primary key
if employee_match:
return render (request, 'employee.html', {'Search': employee_match})
else:
messages.error(request, 'No results found.')
else:
return HttpResponseRedirect('employee/')
return render(request, 'employee.html')
employee.html(查詢和結果查看模板)
<h1>Employee Payroll</h1>
<br><br>
<h2>Enter your ID:</h2>
<form action="/search_employee_form_submit/", method="post"> <!--it will use 'search_employee_form_submit' url after submitting form-->
{% csrf_token %} <!-- added for privacy reasons/security-->
<br>
<input type = "text" name="search_id" placeholder="Enter employee id">
<br><br>
<input type="submit" value="search employee">
</form>
<br><br>
<!-- Code for when your search has results / employee -->
{% if Search %}
{% for k in Search %}
Name:
{{ k.name }} <br>
Position:
{{ k.position }} <br>
Email:
{{ k.email }} <br>
..... etc (this part is working)
Overtime Hour Pay:
{{ k.overtime_hours_pay }}<br>
Gross Income:
{{ k.gross_income }}<br><br>
..... etc (calculated data = doesnt show result)
{% endfor %}
請原諒我的長篇文章,因為我不知道我在哪里遺漏了一些東西。
首先,您引用了 model 中不存在的字段,例如overtime_hours_pay
和gross-income
。 如果您在 model 實例上執行self.someFieldName
,則應在 model 中定義或繼承該字段。 所以這是錯誤的:
self.overtime_hours_pay = self.overtime_hours * 64
你也可以
self
部分並使它們成為普通變量。 看起來像:def salary_calculation(self):
overtime_hours_pay = self.overtime_hours * 64
gross_income = self.basic_pay + self.overtime_hours + self.allowance
self.days_leave = self.days_leave * 512
pagibig = self.basic_pay * 0.01
gsis = self.basic_pay * 0.09
withholdingtax = self.basic_pay * 0.15
philhealth = self.basic_pay * 0.0275 / 2
total_deductions = self.days_leave + pagibig + gsis + withholdingtax + philhealth
net_pay = gross_income - total_deductions
return net_pay
之后,您可以在視圖中計算 net_pay。
...
if employee_match:
# calculation
net_pay = employee_match.salary_calculation()
# then pass this to the template
return render (request, 'employee.html', {'Search': employee_match, 'net_pay': net_pay})
else:
messages.error(request, 'No results found.')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.