我是django
的新手。我的应用程序中有一个表单,其中包含以下代码:
/app/forms.py <==
from django import forms
class ContactForm(forms.Form):
name = forms.CharField(max_length=100)
family = forms.CharField(max_length=250)
phone = forms.IntegerField(max_value=12)
state= forms.CharField(max_length=50)
agreed= forms.BooleanField(initial=True)
why = forms.CharField(max_length=50)
这是我的模特:
class ContactModel(models.Model):
name = models.CharField(max_length=100)
family = models.CharField(max_length=250)
phone = models.IntegerField(max_length=12)
state= models.CharField(max_length=50)
agreed= models.BooleanField(default=True)
why = models.CharField(max_length=50)
def __str__(self):
return self.name + " " + self.family
这是我的观点:
def contact(request):
if request.method == 'post':
form = ContactForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
==> "i dont what can i do here !!!"
else:
form = ContactForm()
return render(request, 'rango/contact.html', {'form': form})
现在我的问题是如何将输入的值保存在模型中。我知道,我可以使用ModelForm
执行此操作,但我需要使用表单执行此操作。
答案 0 :(得分:1)
如果你真的想在没有ModelForm
的情况下这样做,你必须自己创建一个ContactModel
的实例并为其分配所有值。
def contact(request):
if request.method == 'post':
form = ContactForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
obj = ContactModel()
obj.name = cd['name']
obj.family = cd['family']
...
obj.save()
您可以循环遍历cleaned_data
:
if form.is_valid():
cd = form.cleaned_data
obj = ContactModel()
for key, value in cd.iteritems():
setattr(obj, key, value)
obj.save()