Python Django模型,表单字段
我正在努力学习django表格。 我已经创建了model.form它的IntegerField,但django将它们作为字符串 这是我的模特Python Django模型,表单字段,python,django,django-models,django-forms,django-views,Python,Django,Django Models,Django Forms,Django Views,我正在努力学习django表格。 我已经创建了model.form它的IntegerField,但django将它们作为字符串 这是我的模特 from django.db import models class CircuitComponents(models.Model): e1 = models.IntegerField() r1 = models.IntegerField() c1 = models.IntegerField() forms.py from
from django.db import models
class CircuitComponents(models.Model):
e1 = models.IntegerField()
r1 = models.IntegerField()
c1 = models.IntegerField()
forms.py
from django import forms
from .models import CircuitComponents
class CircuitComponentForm(forms.ModelForm):
class Meta:
model = CircuitComponents
fields = '__all__'
还有我的观点
from django.shortcuts import render
from .forms import CircuitComponentForm
def circuit_components_view(request):
if request.method == 'POST':
form = CircuitComponentForm(request.POST)
if form.is_valid():
form.save()
else:
form = CircuitComponentForm()
e1 = request.POST.get('e1')
c1 = request.POST.get('c1')
r1 = request.POST.get('r1')
context = {
'form': form,
'basic_circuit_result': e1 + c1 + r1
}
return render(request, 'basic_circuit.html', context)
还有来自应用程序的ss。我试着对它们进行总结,但结果正如你们在ss上所看到的。。
有谁能帮我解决我没有看到的东西:D?提前谢谢。。
请求。POST
将所有内容都作为字符串,POST参数始终是键-值对,其中键和值都是字符串。它是将其相应地转换为值的形式
可以使用获取由表单确定的值,因此:
def circuit_components_view(request):
basic_circuit_result = None
if request.method == 'POST':
form = CircuitComponentForm(request.POST)
if form.is_valid():
form.save()
basic_circuit_result = form.cleaned_data['e1'] + form..cleaned_data['e1'] + form..cleaned_data['r1']
else:
form = CircuitComponentForm()
context = {
'form': form,
'basic_circuit_result': basic_circuit_result
}
return render(request, 'basic_circuit.html', context)
def电路组件视图(请求):
基本电路结果=无
如果request.method==“POST”:
表单=电路组件表单(request.POST)
如果form.is_有效():
form.save()
基本电路结果=表单.已清理的数据['e1']+表单..已清理的数据['e1']+表单..已清理的数据['r1']
其他:
form=电路组件form()
上下文={
“形式”:形式,
“基本电路结果”:基本电路结果
}
返回render(请求'basic_circuit.html',context)
request.POST
将所有内容作为字符串。它是将其相应地转换为值的形式。然后,我在刷新页面时遇到问题,即在赋值之前引用了局部变量“basic\u circuit\u result”
该错误。@kozmonotosman:这就是为什么要在视图顶部写入basic\u circuit\u result=None
。