[Fixed]-How do I save data from a ModelForm to database in django?

10👍

I found the solution. Rewrote view.py as follows:

def cost(request, offset):
    if request.method == 'POST':
        project  = Project.objects.get(title=offset)
        date     = request.POST.get('date', '')
        cost     = request.POST.get('cost', '')
        cost_obj = Cost(project=project, date=date, cost=cost)
        cost_obj.save()
        return HttpResponseRedirect('/')

The rest of the code has not changed.

14👍

A couple things don’t look right:

  1. Project.objects.filter() will return a queryset. Use Project.objects.get() instead… it will return just a single Project object

  2. You wont need to explicitly set the cost and date, that will be handled by your instance=form.save(commit=False)

  3. You aren’t using the form in your template…

Try this:

Template:

<form action="/cost/{{ project }}/" method="post" accept-charset="utf-8">
     {{form.as_p}}
     <p><input type="submit" value="Add"></p>
</form>

View:

def cost(request, offset):
    if request.method == 'POST':
        form = CostForm(request.POST)
        if form.is_valid():
            instance = form.save(commit=False)
            instance.project = Project.objects.get(title=offset)
            instance.save()
            return HttpResponseRedirect('/')
    else:
        form = CostForm()

    render_to_response('path/to/template.html',{'form':form},context_instance=RequestContext(request))

Also, I think you will need to add blank=True to your models.ForeignKey(Project) in the Cost model. That will allow your ModelForm to validate.

👤Brant

1👍

I did it this way:

def save_model(self, request, obj, form, change):
    obj.save()

To modify something, do it through:

obj.xyz = 'something'
obj.save()
👤Rahul

Leave a comment