尝试在Django

时间:2017-02-01 00:38:24

标签: python html django django-forms

当我尝试分配form.clean_data ['value']时收到KeyError 我正在尝试在django web应用程序中编写一个兴趣计算器,它接受用户输入的初始资本年份和费率并计算最终资本,但是它返回一个关键错误db是sqlite3

在解决方案和设计方面,任何帮助都是一个初学者和所有人。

这里是追溯

回溯:

内部文件“/Users/Andras/miniconda3/lib/python3.5/site-packages/django/core/handlers/exception.py”   39. response = get_response(request)

_get_response中的

文件“/Users/Andras/miniconda3/lib/python3.5/site-packages/django/core/handlers/base.py”   187. response = self.process_exception_by_middleware(e,request)

_get_response中的

文件“/Users/Andras/miniconda3/lib/python3.5/site-packages/django/core/handlers/base.py”   185. response = wrapped_callback(request,* callback_args,** callback_kwargs)

查询中的文件“/Users/Andras/myproject/myapp/views.py”   37. initial = form.cleaned_data ['initial']

异常类型:/ query /的KeyError 例外值:'initial'

views.py

from django.shortcuts import redirect
from django.shortcuts import get_object_or_404, render
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.views import generic
from django.template.loader import get_template
from django.template import Context 
from django.views.generic.base import TemplateView 
from myapp.models import Queries
from django.core import serializers
import os, re, math
from django.template import Context
from django.views.generic import View
from django import forms
from myapp.forms import QueriesForm
import decimal
from django.http import Http404

def get_final(initial, rate, years):
    initial = self.initial
    rate = self.rate
    years = self.years
    calcInterest = (initial*(1+((rate/100)/12))^(12*years))
    final = calcInterest
    return final    


def query(request):
    if request.method == 'POST':

        form = QueriesForm(request.POST)

        if form.is_valid():

            initial = form.cleaned_data['initial']
            rate = form.cleaned_data['rate']
            years = form.cleaned_data['years']

            init1 = Queries.objects.get_initial()
            rate1 = Queries.objects.get_rate()
            years1 = Queries.objects.get_years()
            final1 = get_final(init1, rate1, years1)

            return render (request, 'result.html', {'cacl':final1})

        else:
        raise Http404
    else:

    form = QueriesForm()        

    return render(request, 'index.html', {'form': form})


def index(request):
    template_name = 'index.html'
    return render(request, "index.html", {})

def queries(request):
    template_name = 'queries.html'
    return render(request, "queries.html", {}) 

def result(request):
    template_name = 'result.html'
    return render(request, "result.html", {})

forms.py

from django import forms
from .models import Queries


class QueriesForm(forms.Form):


    initial = forms.NumberInput(attrs={'max_lenght':10, 'requred':True})
    years = forms.NumberInput(attrs={'max_lenght':10, 'requred':True})
    rate = forms.NumberInput(attrs={'max_lenght':10, 'requred':True})

def clean_message(self):
    initial = self.cleaned_data.get("initial")
    years = self.cleaned_data.get("years")
    rate = self.cleaned_data.get("rate")


class Meta:

    model = Queries
    fields = ('initial', 'years', 'rate',)

models.py

from django.db import models
from django.forms import ModelForm

class Queries(models.Model):

    initial = models.DecimalField(max_digits=3, decimal_places = 2)
    years = models.DecimalField(max_digits=3, decimal_places = 2)
    rate = models.DecimalField(max_digits=3, decimal_places = 2)

def get_initial(self):
    return self.initial

def get_years(self):
    return self.years

def get_rate(self):
    return self.rate

urls.py

from django.conf.urls import url
from . import views

app_name = 'myapp'
    urlpatterns = [
    url(r'^$', views.index, name = 'index'),
    url(r'^queries/', views.queries, name = 'queries'),
    url(r'^query/', views.query, name = 'query')

]   

的index.html

{% load staticfiles %}
<!DOCTYPE html>
<head>
    <title>My Cool Savings Calculator</title>
<style>
 h1 {
  padding-bottom: 0em;
  margin-bottom: 0em;
}
table {
  padding-top: 0em;
  margin-top: 0em;
}
</style>
</head>
<body>
<h1>Savings Calculator</h1>

<table>
<form name = "form" action = "{% url 'myapp:query' %}" method='POST'>{% csrf_token %}
<tr>
      <td><label>Initial Capital:</label>

  <td><input type='number' name='initial'></input></td>

 </tr>
 <br>
 <tr>
  <td><label>Number of Years:</label>

  <td><input type='number' name='years' value='5'></input></td>

 </tr>
<br>
<tr>
  <td><label>Interest rate (annual):</label>

  <td><input type='number' name='rate' value='3.5'></input></td>

</tr>
<br>
<tr>
  <td></td>
  <td><input type='submit'></input></td>
</tr>
</form>
 </table>
{% block content %}
{% endblock %}

<h3>Check previous queries <a href='/queries'>here</a></h3>
</body>

results.html

{% extends 'index.html' %}

{% block content %}


<h2>{{calc}}</h2>

{% endblock %}

2 个答案:

答案 0 :(得分:0)

您的attrs参数中存在拼写错误,这可能是导致此问题的原因。

尝试更改这三行:

import { ... } from '../actions/types'

对此:

initial = forms.NumberInput(attrs={'max_lenght':10, 'requred':True})
years = forms.NumberInput(attrs={'max_lenght':10, 'requred':True})
rate = forms.NumberInput(attrs={'max_lenght':10, 'requred':True})

答案 1 :(得分:0)

如上所述,您可能需要更正表格字段中max_length和拼写所需的拼写。

然后我认为您需要实际输出表单而不是常规的html输入。

<form action="{% url 'myapp:query' %}" method="post">
    {% csrf_token %}
    {{ form }}
    <input type="submit" value="Submit" />
</form>

然后也在你的views.py查询函数中,它抛出你可能想要使用的错误.get带有一个回退值。

initial = form.cleaned_data.get('initial', 0)
rate = form.cleaned_data.get('rate', 3.5)
years = form.cleaned_data.get('years', 5)