Klanestro
Klanestro

Reputation: 3215

Taking a Form and saving it into a model

I got this form working Ok but i can't figure out how to save it to the database via the model i know this is a semantic question that i can't figure out Please Help. I'm using django The error is

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

` Donation is my Model and i need to get the information from my form into the Donation Model so i can 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')

The error I get is (1054, "Unknown column 'name' in 'field list'")

Request information

GET
No GET data
POST
Variable    Value
csrfmiddlewaretoken u'nXGN4gdZwk2qxNpP9YIXzvNQI7lKQe5r'
towards u'this'
name    u'this'
description u'that'

Upvotes: 0

Views: 177

Answers (1)

Reinbach
Reinbach

Reputation: 771

change your form class to the following;

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

Then you should be able to change the view.py to the following;

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

See official documentation Creating forms from Models

Upvotes: 2

Related Questions