Extraction datas from forms

随声附和 提交于 2021-01-29 13:46:54

问题


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.

Here is my code:

model

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

form

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

view

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)

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. if you can explain or write a resource where can i read about how does inserting datas work in Django it'd be cool


回答1:


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

On your:

 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 

Later will explain better

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

Hope I could help



来源:https://stackoverflow.com/questions/59805371/extraction-datas-from-forms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!