使用Django,当试图将用户的答案保存到数据库时,它向我显示了一个名称错误。我在views函数中嵌套了一个函数,当我不尝试将数据保存到数据库时,它可以正常工作。但是,一旦我尝试在views函数中插入代码来保存数据,就会产生这个名称错误。下面是包含代码的文件
models.py文件
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
class ansquestions(models.Model):
m_invested = models.CharField(max_length=100)
p_return = models.CharField(max_length=100)
years = models.CharField(max_length=100)
inflation_yes_no = models.CharField(max_length=100)
r_output = models.TextField(default=True)
date_answered = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
forms.py文件
from django import forms
from .models import ansquestions
class ansquestionsForm(forms.ModelForm):
class Meta:
model = ansquestions
fields = ['m_invested', 'p_return', 'years', 'inflation_yes_no', 'r_output', 'date_answered', 'author'
]
views.py文件(注意:fvinvestment函数嵌套在investmentfvcalc函数下。粘贴到此处时,它不会显示为在investmentfvcalc下缩进,但在我的实际代码中,fvinvestment函数缩进并嵌套在InvestmentMetnCalc函数下。)
from django.shortcuts import render
#from django.http import HttpResponse
from .models import ansquestions
from .forms import ansquestionsForm
def investmentfv(request):
idata = { 'tmi':tmi, 'pry':pry, 'ys':ys, 'qinf':qinf }
return render(request, 'fvalueapp/investmentfv.html', idata)
def investmentfvcalc(request):
if request.method == 'POST':
form = ansquestionsForm(request.POST)
if form.is_valid():
total_i = request.POST.get["m_invested", '']
perc_r = request.POST.get["p_return", '']
years_i = request.POST.get["years", '']
makeup_infl = request.POST.get["inflation_yes_no", '']
ansquestions_obj = ansquestions(m_invested=total_i, p_return=perc_r, years=years_i, inflation_yes_no=makeup_infl)
ansquestions_obj.save()
def fvinvestment():
global fv_i_value
global r_output
#global makeup_infl ( global variable might be needed for technique for above. as error says makeup_inf is not defined )
if makeup_infl=='no':
i_return = (float(perc_r))
elif makeup_infl=='yes' and int(years_i)<=5:
i_return = (2+float(perc_r))
elif makeup_infl=='yes' and int(years_i)>5 and int(years_i)<=9.99 :
i_return = (4 + float(perc_r))
elif makeup_infl=='yes' and int(years_i)>= 10 :
i_return = ( 6 + float(perc_r))
fv_i_value = int(total_i) * (1 + (i_return)*.01) ** int(years_i)
r_output = 'Your money would grow to the total of ' + str(fv_i_value) +' dollars at the end of this timeframe.'
fvinvestment()
idata = { 'tmi':tmi, 'pry':pry, 'ys':ys, 'qinf':qinf, 'r_output': r_output }
return render (request, 'fvalueapp/fvinvestmentcalcresults.html', idata)
错误:
运行上述代码时,它会给我错误“NameError at investmentfv/InvestmentTFVCALC”“在封闭范围内的赋值之前引用的自由变量'Component_infl'”i,然后将变量“Component_infl”作为全局变量放入fvinvestment函数中,这将产生错误“名称错误-未定义名称‘补充信息’
将fvinvestment更改为global scope,传入以下变量:年份和构成
这也将解决您的化妆信息未定义错误
相关问题 更多 >
编程相关推荐