如何将数据从ModelForm保存到django中的数据库?

时间:2010-05-14 20:03:03

标签: python django

我有一个模特:

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

对于模型,我创建了一个ModelForm类:

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

view.py

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

和下一个模板:

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

问题

如何将数据从表单保存到数据库?

一些其他信息:

model.py包含

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

我的尝试

我尝试以下一种方式实现解决方案(注意:offset =项目名称):

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

但它不起作用:(

3 个答案:

答案 0 :(得分:13)

有些事情看起来并不合适:

  1. Project.objects.filter()将返回一个查询集。请改用Project.objects.get() ...它只返回一个Project对象

  2. 您无需明确设置费用和日期,这将由instance=form.save(commit=False)

  3. 处理
  4. 您没有在模板中使用该表单...

  5. 试试这个:

    模板:

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

    查看:

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

    此外,我认为您需要将blank=True添加到models.ForeignKey(Project)模型中的Cost。这将允许您的ModelForm进行验证。

答案 1 :(得分:10)

我找到了解决方案。重写view.py如下:

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('/')

其余代码没有改变。

答案 2 :(得分:1)

我是这样做的:

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

要修改某些内容,请执行以下操作:

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