1

我已经为此工作了一段时间,我决定寻求您的帮助。我有一个正在进行的项目,我正在使用 django 框架来构建站点。我有一个请求用户输入的 html 页面,我已经能够使用form.cleaned_data['']. 一种

#This is my views.py;



 from django.shortcuts import render_to_response
    from django.template import RequestContext

    from forms import CarloanForm


    def index(request):
        form = CarloanForm()
        if request.POST:
            form = CarloanForm(request.POST)
            if form.is_valid():
                form.save()
        else:
            form = CarloanForm()
        return render_to_response('carloan/index.html', {'form': form},
                      context_instance=RequestContext(request))

#I am extracting the user inputs using;

amount_of_vehicle = form.cleaned_data['cost_of_vehicle_Naira'] 
tenure = form.cleaned_data['loan_repayment_tenure_Months']
interest_rate = form.cleaned_data['interest_rate_Percentage']
equity = form.cleaned_data['equity_contrib_rate_Percentage']
depreciation_rate = form.cleaned_data['depreciation_rate_Percentage']

我需要做但不知道如何去做的是;

  1. 对数据进行一些操作(使用提取form.cleaned_data['']),我为此编写了一些代码行;

    class LoanCalc:
        def __init__(self,amount_of_vehicle,tenure,interest_rate,equity,depreciation_rate):
            self.amount_of_vehicle = float(amount_of_vehicle)
            self.tenure = float(tenure)
            self.interest_rate = float(interest_rate)
            self.equity = float(equity)
            self.depreciation_rate = float(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 + user.interest())
        def processing_fee(self):
            return 0.0025 *(self.amount_of_vehicle + user.interest())
        def legal_fee(self):
            return 0.0075 * (self.amount_of_vehicle + user.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 LoanPaymentPlan(self):
            months = 1
            total_amount = self.amount_of_vehicle+user.interest()+user.management_fee()+user.processing_fee()+user.legal_fee()+user.residual_amount()
            upfront_payment = user.management_fee()+user.processing_fee()+user.legal_fee()+user.equity_contribution()+user.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 Calculator App'
    

我想对提取的数据执行上面代码中的操作。

  1. 我正在考虑以这样的方式进行操作;

创建一个空字典;

    user = {}
    user = LoanCalc(amount_of_vehicle,tenure,interest_rate,equity,depreciation_rate)
    result= user.interest()
    result1 = user.management_fee()
     .           .
     .           .
     .           .
    result10 = user.LoanPaymentPlan()
  1. 将从(问题 2)获得的结果传递给生成表单的同一模板。

请帮帮我,我对 django 还是很陌生。谢谢

这是我得到的引用错误的完整堆栈:

Environment:


Request Method: GET
Request URL: http://127.0.0.1:9000/result/

Django Version: 1.4.1
Python Version: 2.5.4
Installed Applications:
('django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.sites',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'django.contrib.admin',
 'carloan')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware')


Traceback:
File "C:\Python25\Lib\site-packages\django\core\handlers\base.py" in get_response
  111.                         response = callback(request, *callback_args, **callback_kwargs)
File "C:\Users\AJIBIKE\Documents\Circuit Atlantic\calculator\carloan\views.py" in result_page
  226.         'carloan': instance,

def result_page(request):
    if request.POST:
        form = Carloan_formForm(request.POST)
        if form.is_valid():
            instance = form.save(commit=False)
            instance.interest = (instance.interest_rate/100) * instance.amount_of_vehicle * (instance.tenure/12)
            instance.save()
    else:
        form = Carloan_formForm()
    return render_to_response('carloan/result.html', {'carloan': instance,'form': form},
                  context_instance=RequestContext(request))


Exception Type: UnboundLocalError at /result/
Exception Value: local variable 'instance' referenced before assignment

最新的

from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponseRedirect, HttpResponse

from forms import Carloan_formForm


def index(request):
    if request.POST:
        form = Carloan_formForm(request.POST)
        if form.is_valid():
            instance = form.save()
            return HttpResponseRedirect ('/result/')
    form = Carloan_formForm()
    kwvars = {
            'form': form,
            }
    return render_to_response('carloan/index.html', kwvars,
                  context_instance=RequestContext(request))


def result_page(request):
    instance = None
    if request.POST:
        form = Carloan_formForm(request.POST)
        if form.is_valid():
            instance = form.save(commit=False)
            instance.interest = (instance.interest_rate_Percentage/100) * instance.cost_of_vehicle_Naira * (instance.loan_repayment_tenure_Months/12)
            instance.management_fee = 0.01 * (instance.cost_of_vehicle_Naira + instance.interest)
            instance.processing_fee = 0.0025 * (instance.cost_of_vehicle_Naira + instance.interest)
            instance.legal_fee = 0.0075 * (instance.cost_of_vehicle_Naira + instance.interest)
           #i get syntax error starting from this line, and when i comment it out and the lines below, there is no syntax error.
            instance.residual_amount = 0.01 * ((instance.cost_of_vehicle_Naira - ((instance.depreciation_rate_Percentage/100) * instance.cost_of_vehicle_Naira * (instance.tenure/12))) 
            instance.equity_contribution = (instance.equity_contrib_rate_Percentage/100) * instance.cost_of_vehicle_Naira)
            instance.save()
    else:
        form = Carloan_formForm()
    return render_to_response('carloan/result.html', {'instance': instance, 'form': form},
                  context_instance=RequestContext(request))
forms.py

from django import forms
from django.forms import ModelForm

from models import Carloan_form

class Carloan_formForm(ModelForm):
    class Meta:
        model = Carloan_form
        exclude = ('interest', 'management_fee', 'processing_fee', 'legal_fee', \
                   'residual_amount', 'equity_contribution')
4

2 回答 2

1

一种更简单的方法是将会话中的数据存储在一个视图中,然后在下一个视图中检索它。文档会有所帮助。1

话虽如此 - 还有其他一些方法可以解决这个问题。在 SO 上已不止一次讨论过它:

于 2012-10-29T15:28:12.943 回答
1

1 保存在 Django Administration 中对提取的数据执行的操作的结果。(注意:我已经知道如何保存用户输入)

创建一个模型来保存用户的条目。app/models.py

class Carloan(models.Model) :
    # In addition to your model fields add the functions that are part of your LoanCalc
    ...

然后创建一个 ModelForm:app/forms.py

class CarLoanForm(forms.ModelForm) :
    class Meta:
        model = Carloan

以与通常相同的方式使用 CarLoanForm,除了:app/views.py

if request.POST:
    form = CarloanForm(request.POST)
    if form.is_valid():    
        carloan = form.save()
        #pass carloan (the instance) to the template and 
        #call its functions(from LoanCalc) instead of 
        #passing all of the values separately

最后,注册这个模型,让它出现在管理部分app/admin.py

from django.contrib import admin
from app.models import Carloan

admin.sites.register(Carloan)

2 我将页面分为两部分(一个用于表单,另一个用于结果),我想将结果传递到页面的一半以使用户能够看到它。

使用上述步骤,carloan 将被传递给视图。继续渲染它的值。

此外:

重构索引

您的索引定义应该稍微重构,否则您的 POST 绑定表单将永远不会进入模板:

def index(request):
    if request.POST:
        form = CarloanForm(request.POST)
        if form.is_valid():
            instance = form.save()
    else :
        form = CarloanForm()

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

重构你的 ModelForm

对数据执行一些操作(使用 form.cleaned_data[''] 提取),我为此编写了一些代码行;- 使用 ModelForm 而不是常规的 django 表单,您将获得一个模型实例,其中已经填写了用户的值,您可以使用instance.field引用它们。

我想对提取的数据执行上面代码中的操作。- 您计划为其计算值的字段列在排除中,它们不会影响表单验证。

class CarLoanForm(forms.ModelForm) :
    class Meta:
        model = Carloan
        # exclude fields that are calculated from user input
        # NOTE: these fields must be in your model
        exclude = ('interest', 'management_fee'...) 

重构结果页面

对数据执行一些操作(使用 form.cleaned_data[''] 提取),我为此编写了一些代码行;

  • 在 form.is_valid 检查下的 results_page 中,有一行:instance = form.save(commit=False)这将获取用户在尚未保存的 Carloan 模型实例中提交的所有值。
  • 再往下:instance.interest = (instance.interest_rate/100) * instance.amount_of_vehicle *(instance.tenure/12)在这一行中,我正在计算一个排除的字段值(此计算是您的代码的副本)。
  • 最后(在完成对数据的所有操作之后)我保存模型的实例。
  • 然后将实例传递给模板进行显示。

代码:

def result_page(request):
    if request.POST:
        form = CarloanForm(request.POST)
        if form.is_valid():
            # get an instance from the form but don't save it
            instance = form.save(commit=False)
            # calculate excluded field values
            instance.interest = (instance.interest_rate/100) * instance.amount_of_vehicle *(instance.tenure/12)
            ...
            # after you have calculated all of the excluded fields save the instance
            instance.save()

    else :
        form = CarloanForm()

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

错误:

reference before error assignment- 它说什么在分配之前被引用?请粘贴整个堆栈跟踪。

于 2012-10-29T15:47:37.010 回答