我尝试将django poll应用程序应用于我自己的应用程序(IMC计算器),以改进并为python/django的第一步构建一个小项目。在
我试着保存我的第一个表单的数据accueil.html:
<form action="" method="post">
<table>
{{ form.as_table }}
</table>
<input type ="submit" value="Submit">
</form>
这是我的表单.py:
^{pr2}$这是我的模型.py:
from django.db import models
from django.forms import ModelForm
class Individu(models.Model):
nom = models.CharField(max_length=100)
prenom = models.CharField(max_length= 100)
anniversaire = models.DateField()
taille = models.IntegerField()
poids = models.IntegerField()
def __unicode__(self):
return self.nom
class ImcResultat(models.Model):
individu = models.ManyToManyField(Individu)
imc = models.IntegerField()
date_imc = models.DateField()
class IndividuForm(ModelForm):
class Meta:
model = Individu
class ImcResultatForm(ModelForm):
class Meta:
model = ImcResultat
最后我的*视图.py*在这里: 问题出在第13行*a=cd.创建()*当我试图将数据从表单保存到数据库时。在
from django.shortcuts import render_to_response
from django.http import HttpResponse, HttpResponseRedirect
from models import Individu, ImcResultat
from forms import IndividuDataForm
def accueil(request):
if request.method == 'POST':
form = IndividuDataForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
a = cd.create() **#this is the problem**
return HttpResponseRedirect('/accueil/page2/')
else:
form = IndividuDataForm()
return render_to_response('accueil.html', {'form':form})
def page2(request):
return render_to_response('page2.html')
我想是在第一部分视图.py我的函数不能很好地工作,它没有把表单保存在数据库中。 def ACCEIL(请求):
if request.method == 'POST':
form = IndividuDataForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
a = cd.create() **#this is the problem**
return HttpResponseRedirect('/accueil/page2/')
在检查表单是否有效之后,我清理表单中的数据,然后尝试保存它。 我得到了一个错误:
Exception Type: AttributeError
Exception Value: 'dict' object has no attribute 'create'
我想它来自词典,但在我的代码中我从未使用过{}作为词典列表。 所以我不知道,就困在学习的过程中。在
谢谢你的帮助,我希望从我的第一个stackoverflow帖子我没有犯太多的错误。在
如果您只想将提交的数据保存为django ModelForm,请使用窗体保存(). 在
参见:https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#s-the-save-method
这将使用已清理/验证的数据。在
你可以用已清理的数据如果您需要执行其他操作而不是用模型实例保存它。在
丹尼尔的回答更正确
不过,我会留下我的原始答案,只是为了文档链接。在
在已清理的数据没有dictionary()和create()类型。我想你是想为数据库中的数据创建一个模型?在
看看Can a dictionary be passed to django models on create?从字典中创建一个模型。例如:
^{pr2}$下面是处理表单数据的文档。在
https://docs.djangoproject.com/en/dev/topics/forms/#processing-the-data-from-a-form
祝你好运!在
您应该使用ModelForm,它将自动定义字段以匹配模型上的字段。然后可以调用
form.save()
直接从表单创建实例。在相关问题 更多 >
编程相关推荐