我有一个模特:
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()
但它不起作用:(
答案 0 :(得分:13)
有些事情看起来并不合适:
Project.objects.filter()
将返回一个查询集。请改用Project.objects.get()
...它只返回一个Project
对象
您无需明确设置费用和日期,这将由instance=form.save(commit=False)
您没有在模板中使用该表单...
试试这个:
模板:
<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()