How do I save data from a ModelForm to database in django?


Question

I have a model:

class Cost(models.Model):
    project = models.ForeignKey(Project)
    cost = models.FloatField()
    date = models.DateField()

For the model I created a ModelForm class:

class CostForm(ModelForm):
    class Meta:
        model = Cost
        fields = ['date', 'cost']

with view.py:

def cost(request, offset):
    if request.method == 'POST':
        # NOTE: How to save the data in DB?
        return HttpResponseRedirect('/')
    else:
        form = CostForm()

and next template:

<form action="/cost/{{ project }}/" method="post" accept-charset="utf-8">
    <label for="date">Date:</label><input type="text" name="date" value={{ current_date }} id="date" />
    <label for="cost">Cost:</label><input type="text" name="cost" value="0" id="cost" />
    <p><input type="submit" value="Add"></p>
</form>

Question

How I can save the data from the form to the database?

Some additional information:

model.py contains

class Project(models.Model):
    title = models.CharField(max_length=150)
    url = models.URLField()
    manager = models.ForeignKey(User)
    timestamp = models.DateTimeField()

My attempt

I tried to implement the solution in a next way (note: offset = project name):

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.filter(title=offset)
            instance.date = request.date
            instance.cost = request.cost
            instance.save()
        return HttpResponseRedirect('/')
    else:
        form = CostForm()

But it does not work :(

1
13
5/5/2017 8:46:01 AM

Accepted Answer

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.

10
8/14/2017 8:29:53 PM

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.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon