在django中,如何读取表单数据,执行操作,然后存储到数据库中?
Posted
技术标签:
【中文标题】在django中,如何读取表单数据,执行操作,然后存储到数据库中?【英文标题】:In django,How to read form data, perform operation and then store in database? 【发布时间】:2014-09-24 05:51:01 【问题描述】:这是我的模型:
class Expense(models.Model):
Item= models.CharField(max_length=100)
description= models.CharField(max_length=1000)
Amount=models.DecimalField(max_digits=18, decimal_places=2, default=0)
date = models.DateField(default=date.today())
category = models.ForeignKey(ExpenseCategory) # either expense or income
我想编写一个代码来读取 html 表单上 textarea 中的值
"Vegitable 10kg 100 Taxi 10kms 200 mobile brothers 200 clothes 2shirts 1500.50"
然后我会将其拆分为不同的列表(我为此编写了代码):
item=[vegitable,Taxi,mobile,clothes]
description = [10kg,10kms,brothes,2shirts]
amount=[100,200,200,1500.50]
现在我想编写一个代码来将上面的列表(04 条记录)连同日期和类别一起存储到上面的模型(实际上是数据库)中。数据库必须如下所示。
Item description Amount date category
____________________________________________________
Vegitable 10kg 100 28/09/2014 expense
Taxi 10kms 200 28/09/2014 expense
mobile brothers 200 28/09/2014 expense
clothes 2shirts 1500.50 28/09/2014 expense
注意:这里的日期是今天的日期,类别是费用
【问题讨论】:
【参考方案1】:经过一些适当的python格式化后,数据如下所示:
item=['vegitable','Taxi','mobile','clothes']
amount=[100,200,200,1500.50]
description = ['10kg','10kms','brothes','2shirts']
根据您的模型重新排列数据:
import datetime
from decimal import Decimal as D
category = ExpenseCategory.objects.get(name='expense')
rows = map(lambda i,a,d: 'Item':i, 'Amount':D(a), 'description':d, item, amount, description)
for row in rows:
expense = Expense(**row)
expense.category = category
expense.date = datetime.datetime.now()
expense.save()
更新:
集成取决于您的表单处理:
把数据的格式放在Form.clean
:
class ExpensesForm(forms.Form):
def clean(self):
cleaned_data = super(ExpensesForm, self).clean()
# Your code for splitting things up goes here
cleaned_data['expenses'] = map(lambda i,a,d: 'Item':i, 'Amount':D(a), 'description':d, item, amount, description)
return cleaned_data
在你看来你可以做某事。像这样:
def my_view(request):
...
if form.is_valid()
for row in form.cleaned_data['expenses']:
expense = Expense(**row)
expense.category = category
expense.date = datetime.datetime.now()
expense.save()
...
【讨论】:
谢谢你的回答......你能告诉我在哪里插入这个代码......我是 django 的新手......我很感谢你的宝贵想法和时间..... 每一个很好的行都有正确的数据但数据库没有更新:( is_valid() 缺少 1 个必需的位置参数:'self' ........这是我遇到的错误 非常感谢@tc77 我终于完成了任务我已经写了一个单独的答案【参考方案2】:def save(self, *args, **kwargs):
category = ExpenseCategory.objects.get(description='expense')
# code for split
str=self.description
lis=str.split()
description=lis[0::3]
item=lis[1::3]
amount=lis[2::3]
rows = map(lambda d,a: 'description':d,'amount':D(a), description, amount )
for row in rows:
print("I am in start of for")
expense = Expense(**row)
expense.category = category
expense.date = self.date
print("%s %s %s %s" % (self.description, self.amount,self.category,self.date))
print("%s %s %s %s" % (expense.description, expense.amount,expense.category,expense.date))
expense.save()
#super(Blog, self).save(*args, **kwargs) # Call the "real" save() method
super(Expense, expense).save(*args, **kwargs) # Call the "real" save() method
print("I am in end of for")
上面的代码我已经写在models.py中了
【讨论】:
以上是关于在django中,如何读取表单数据,执行操作,然后存储到数据库中?的主要内容,如果未能解决你的问题,请参考以下文章
Django 表单字段验证 - 如何判断操作是插入还是更新?