从表格中提取数据 [英] Extraction datas from forms

查看:77
本文介绍了从表格中提取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始学习Django,现在我正在尝试了解如何在db中插入数据,如何使用模板和ect等中的数据.我的问题是关于从模板中的form(Meta类)提取数据.

I've just start to learn Django and now I'm trying understand how to insert datas in db, how to work with datas from templates and ect. My question is about extracting datas from form(Meta class) in template.

这是我的代码:

模型

class Worker(models.Model):
POSITION_SHOICE = (
    ('MANAGER', 'MANAGER'),
    ('developer', 'DEVELOPER'),
    ('teamlead', 'TEAMLEAD'),
    ('pm', 'PM'),
    ('hr', 'HR'),
)
f_name = models.CharField(max_length=50)
s_name = models.CharField(max_length=50)
position = models.CharField(max_length=10, choices=POSITION_SHOICE, default='developer')
work_time = models.DecimalField(max_digits=1000, decimal_places=0)
cost_in_hour = models.DecimalField(max_digits=1000, decimal_places=2)

salary = models.DecimalField(max_digits=10000000, decimal_places=2, default=0)

在插入数据之前,应按以下方式计算饱和度:薪水=工作时间*成本_小时数

before inserting datas salaty should be calculate in this way: salary = work_time*cost_in_hour

表格

class WorkerForm(forms.ModelForm):
class Meta:
    model = Worker
    fields = {
        'f_name',
        's_name',
        'position',
        'work_time',
        'cost_in_hour',
    }

视图

def worker_create_view(request):
form = WorkerForm(request.POST or None)
if form.is_valid():
    form.save()
    form = WorkerForm()
context = {
    'form': form
}
return render(request, "workers/worker_create.html", context)

我实际上无法理解如何从名称为'work_time'和'cost_in_hour'的字典项中提取数据.然后计算薪水,插入字典并发送到数据库.

I actually cannot understand how can I extract datas from dictionary items with name 'work_time' and 'cost_in_hour'. then calculate salary, insert into dictionary and send to database.

P.S.如果您可以解释或编写资源,在哪里可以阅读到有关如何在Django中插入数据的信息,那将很酷

P.S. if you can explain or write a resource where can i read about how does inserting datas work in Django it'd be cool

推荐答案

从Android应答.稍后将其放在适当的代码"表单上.

Answering from the android. Later will put this on proper "code" form.

关于您:

 if form.is_valid():
      instance = form.save(commit=False)

      #do what you want with the form fields like
       instance.salary = instance.work_time *cost_in_hour
      # then
       instance.save()

      #continue to response 

稍后会更好地解释

您还可以在表单本身上覆盖表单保存方法,以获取更清晰的视图.

You can also override the form save method on the form itself for a more clean view.

希望我能帮忙

这篇关于从表格中提取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆