0

我让这个表格工作正常,但我不知道如何通过模型将它保存到数据库中,我知道这是一个我无法弄清楚的语义问题请帮助。我正在使用 django 错误是

 D = Donation(user=request.user,name=form.cleaned_data['name'],description=cd['descri‌​ption']) 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'
4

1 回答 1

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))

参见官方文档从模型创建表单

于 2012-09-05T18:26:04.850 回答