[Answer]-In django,How to read form data, perform operation and then store in database?

1👍

After some proper python formatting the data looks like this:

item=['vegitable','Taxi','mobile','clothes']
amount=[100,200,200,1500.50]
description = ['10kg','10kms','brothes','2shirts']

To rearrange the data according to your model:

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

UPDATE:

The integration depends on your form handling:

Put the formatting of the data at 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

At your view you may do sth. like this:

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

0👍

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

The above code I have written in models.py

Leave a comment