title: How do I save data from a ModelForm to database in django?
body: <p>I have a model:</p>
  
  <pre><code>class Cost(models.Model):
      project = models.ForeignKey(Project)
      cost = models.FloatField()
      date = models.DateField()
  </code></pre>
  
  <p>For the model I created a <code>ModelForm</code> class:</p>
  
  <pre><code>class CostForm(ModelForm):
      class Meta:
          model = Cost
          fields = ['date', 'cost']
  </code></pre>
  
  <p>with <code>view.py</code>:</p>
  
  <pre><code>def cost(request, offset):
      if request.method == 'POST':
          # NOTE: How to save the data in DB?
          return HttpResponseRedirect('/')
      else:
          form = CostForm()
  </code></pre>
  
  <p>and next template:</p>
  
  <pre><code>&lt;form action="/cost/{{ project }}/" method="post" accept-charset="utf-8"&gt;
      &lt;label for="date"&gt;Date:&lt;/label&gt;&lt;input type="text" name="date" value={{ current_date }} id="date" /&gt;
      &lt;label for="cost"&gt;Cost:&lt;/label&gt;&lt;input type="text" name="cost" value="0" id="cost" /&gt;
      &lt;p&gt;&lt;input type="submit" value="Add"&gt;&lt;/p&gt;
  &lt;/form&gt;
  </code></pre>
  
  <h2>Question</h2>
  
  <p><em>How I can save the data from the form to the database?</em></p>
  
  <h3>Some additional information:</h3>
  
  <p><code>model.py</code> contains</p>
  
  <pre><code>class Project(models.Model):
      title = models.CharField(max_length=150)
      url = models.URLField()
      manager = models.ForeignKey(User)
      timestamp = models.DateTimeField()
  </code></pre>
  
  <h3>My attempt</h3>
  
  <p>I tried to implement the solution in a next way (note: offset = project name):</p>
  
  <pre><code>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()
  </code></pre>
  
  <p>But it does not work :(</p>