我得到这个表格工作好但我无法弄清楚如何通过模型将它保存到数据库我知道这是一个语义问题,我无法弄清楚请帮助。我正在使用django错误是
D = Donation(user=request.user,name=form.cleaned_data['name'],description=cd['description']) D.save()
views.py
def donate(request):
if request.method == 'POST':
form = DonationForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
D = Donation(user=request.user,name=form.cleaned_data['name'],description=cd['description'])
D.save()
return HttpResponseRedirect('/test/')
else:
form =DonationForm()
return render_to_response('addaDonation.html',{'form': form},context_instance=RequestContext(request))
` 捐赠是我的模型,我需要从我的表格中获取信息到捐赠模型,所以我可以D.save
class DonationForm(forms.Form):
name = forms.CharField(max_length=50)
description = forms.CharField(max_length=3000)
towards = forms.CharField()
#image = forms.ImageField()
class Donation (models.Model):
user = models.ForeignKey(User)
name = models.CharField(max_length=50)
description = models.CharField(max_length=3000)
towards = models.ForeignKey(NonProfit)
image = models.ImageField(upload_to='photos/%Y/%m/%d')
我得到的错误是 (1054,“字段列表'中的未知列'名称'”)
Request information
GET
No GET data
POST
Variable Value
csrfmiddlewaretoken u'nXGN4gdZwk2qxNpP9YIXzvNQI7lKQe5r'
towards u'this'
name u'this'
description u'that'
答案 0 :(得分:2)
将表单类更改为以下内容;
from django.forms import ModelForm
class DonationForm(ModelForm):
class Meta:
class = Donation
exclude = ("user", )
def save(self, user):
donation = super(DonationForm, self).save(commit=False)
donation.user = user
donation.save()
return donation
然后您应该能够将view.py更改为以下内容;
def donate(request):
if request.method == 'POST':
form = DonationForm(request.POST, request.FILES)
if form.is_valid():
form.save(request.user)
return HttpResponseRedirect('/test/')
else:
form = DonationForm()
return render_to_response('addaDonation.html',{'form': form},context_instance=RequestContext(request))
请参阅官方文档Creating forms from Models