如何在django中保存从视图到数据库的响应

时间:2012-11-14 08:31:08

标签: html django

models.py

from django.db import models
from django.contrib.auth.models import User

from registeredmember.models import Registeredmember


# Create your models here.

class Carloan_form(models.Model):
    cost_of_vehicle_Naira               = models.DecimalField(max_digits=10, decimal_places=2)
    loan_repayment_tenure_Months        = models.DecimalField(max_digits=10, decimal_places=2)
    interest_rate_Percentage            = models.DecimalField(max_digits=10, decimal_places=2)
    equity_contrib_rate_Percentage      = models.DecimalField(max_digits=10, decimal_places=2)
    depreciation_rate_Percentage        = models.DecimalField(max_digits=10, decimal_places=2)
    user                                = models.ForeignKey(User, null=True)
    time                                = models.DateTimeField(auto_now_add=True)

    def __unicode__(self):
            return unicode(self.user)    

forms.py

from django import forms
from django.forms import ModelForm

from models import Carloan_form

class Carloan_formForm(ModelForm):
    cost_of_vehicle_Naira           = forms.DecimalField(label=(u'Cost of vehicle (in Naira)'))
    loan_repayment_tenure_Months    = forms.DecimalField(label=(u'Loan tenure (in Months)'))
    interest_rate_Percentage        = forms.DecimalField(label=(u'Interest rate (in %)'))
    equity_contrib_rate_Percentage  = forms.DecimalField(label=(u'Equity contribution rate (in %)'))
    depreciation_rate_Percentage    = forms.DecimalField(label=(u'Depreciation rate (in %)'))
    class Meta:
        model = Carloan_form
        exclude = ('user',)

views.py

from django.contrib.auth.models import User
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponseRedirect, HttpResponse
from django.contrib.auth.decorators import login_required


from forms import Carloan_formForm
@login_required
def index(request):
    form = Carloan_formForm()
    if request.POST:
        form = Carloan_formForm(request.POST)
        if form.is_valid():
            form.save()

            #Collection and Assignment of User input
            amount_of_vehicle = float(form.cleaned_data['cost_of_vehicle_Naira'])
            tenure = float(form.cleaned_data['loan_repayment_tenure_Months'])
            interest_rate = float(form.cleaned_data['interest_rate_Percentage'])
            equity = float(form.cleaned_data['equity_contrib_rate_Percentage'])
            depreciation_rate = float(form.cleaned_data['depreciation_rate_Percentage'])
            carloan = form.save(commit=False)
            carloan.user = request.user
            carloan.save()

            #Class Definition
            class LoanCalc:
                def __init__(self,amount_of_vehicle,tenure,interest_rate,equity,depreciation_rate):
                    self.amount_of_vehicle = amount_of_vehicle
                    self.tenure = tenure
                    self.interest_rate = interest_rate
                    self.equity = equity
                    self.depreciation_rate = depreciation_rate
                def interest(self):
                      return((self.interest_rate/100) * self.amount_of_vehicle *(self.tenure/12))
                def management_fee(self):
                    return 0.01 * (self.amount_of_vehicle + self.interest())
                def processing_fee(self):
                    return 0.0025 *(self.amount_of_vehicle + self.interest())
                def legal_fee(self):
                    return 0.0075 *(self.amount_of_vehicle + self.interest())
                def residual_amount(self):
                    return 0.01 * (self.amount_of_vehicle - ((self.depreciation_rate/100) * self.amount_of_vehicle *(self.tenure/12)))
                def equity_contribution(self):
                    return (self.equity/100) * self.amount_of_vehicle
                def total_amount(self):
                    return self.amount_of_vehicle+self.interest()+self.management_fee()+self.processing_fee()+self.legal_fee()+self.residual_amount() 
                def upfront_payment(self):
                    return self.management_fee() + self.processing_fee() + self.legal_fee() + self.equity_contribution() + self.residual_amount()
                def opening_balance(self):
                    return self.total_amount() - self.upfront_payment()
                def monthly_instalment(self):
                    return self.opening_balance()/self.tenure
                def LoanPaymentPlan(self):
                    months = 1
                    total_amount = self.amount_of_vehicle+self.interest()+self.management_fee()+self.processing_fee()+self.legal_fee()+self.residual_amount()
                    upfront_payment = self.management_fee()+self.processing_fee()+self.legal_fee()+self.equity_contribution()+self.residual_amount()
                    opening_balance = total_amount - upfront_payment
                    balance = opening_balance
                    while months <= self.tenure:
                        if balance > 0:
                            monthly_instalment =(opening_balance/self.tenure)
                            monthly_interest = (((self.interest_rate/100) * balance)/ 12)
                            loan_payment = monthly_instalment - monthly_interest
                            closing_balance = balance - monthly_instalment
                            print '  ',months,'  ',round(balance,2),'   ', round(monthly_instalment,2),'        ',round(monthly_interest,2) \
                            , '       ',' ',round(loan_payment,2),'     ',round(closing_balance,2)
                            balance = closing_balance
                            months += 1
                    return 'Thank you for using the Loan Calc App'

            #Creation of an instance with the name 'calc'
            calc = LoanCalc(amount_of_vehicle,tenure,interest_rate,equity,depreciation_rate)
            amountofVehicle = amount_of_vehicle
            interest = calc.interest()
            managementFee = calc.management_fee()
            processingFee = calc.processing_fee()
            legalFee = calc.legal_fee()
            residualAmount = calc.residual_amount()
            equityContribution = calc.equity_contribution()
            totalAmount = calc.total_amount()
            upfrontPayment = calc.upfront_payment()
            openingBalance = calc.opening_balance()
            loanpaymentplan =calc.LoanPaymentPlan()



            #An empty form to be displayed alongside the result
            forms = Carloan_formForm()

            #Renders a template that displays the result
            return render_to_response('carloan/result.html', {'form': forms, 'result':amountofVehicle , 'result1': interest, 'result2': managementFee, 'result3': processingFee,
                                                              'result4': legalFee, 'result5': residualAmount, 'result6': equityContribution, 'result7': totalAmount,
                                                              'result8': upfrontPayment, 'result9':openingBalance, 'result10': loanpaymentplan},
                          context_instance=RequestContext(request))
    #If the user doesn't submit the form, it displays an empty form
    else:
        form = Carloan_formForm()
    #Rendering a that template that displays an empty form
    return render_to_response('carloan/index.html', {'form': form},
                          context_instance=RequestContext(request))

我的问题是;

  1. 有没有办法可以保存结果传递给模板?
  2. 有没有办法可以发送我在Q1中保存的结果。上面,并通过电子邮件发送给用户(仅在用户需要时)?
  3. 3.'result10':我正在传递给模板的loanpaymentplan`,只打印一行并且没有经过循环并打印所有内容,但同时它在命令提示符中打印所有内容(仍在开发中)。可能有什么不对?

1 个答案:

答案 0 :(得分:1)

你可以看一下这样的事情:

模型

from django.db import models
class LoanCalc(models.Model):
    amount_of_vehicle = models.DecimalField()
    tenure = models.DecimalField()
    interest_rate = models.DecimalField()
    equity = models.DecimalField()
    depreciation_rate = models.DecimalField()

    def interest(self):
        return((self.interest_rate/100) * self.amount_of_vehicle *(self.tenure/12))
    def management_fee(self):
        return 0.01 * (self.amount_of_vehicle + self.interest())

视图

# views.py
from django.core.mail import send_mail
from django.template.loader import get_template
from django.template import Context

from .models import LoanCalc

def loan_calc(request, **kwargs):
    calc = LoanCalc.objects.create(**kwargs)

    # Render your calc model in a template and use send_mail to email it
    send_mail(
        'This is your loan calculation!',
        get_template('carloan/email.txt').render(
            Context({
                'calc': calc,
            })
        ),
        'you@example.com',
        ['receiver@gexample.com']
    )

    return render_to_response('carloan/result.html',
                              {'form': forms, 'calc': calc}
                              context_instance=RequestContext(request))

视图模板

# result.html
<table>
    <tr>
       <td>Interest</td>
       <td>{{ calc.interest }}</td>
    </tr>
    <tr>
       <td>Management fee</td>
       <td>{{ calc.management_fee }}</td>
    </tr>
</table>

电子邮件模板

# email.txt
Hi, this is your loan calculation overview:

Interest: {{ calc.interest }}
Management fee: {{ calc.management_fee }}