简体   繁体   English

Django UpdateView更新在视图中

[英]Django UpdateView update filed in view

I am making simple app in django, I have UpdateView for updating my model once is in the database. 我在django中制作简单的应用程序,我有一个UpdateView用于在数据库中更新我的模型。 I update form I didn't include all fields I would like to update some of them in the background. 我更新表格我没有包括我想在后台更新其中一些字段的所有字段。 Something like: 就像是:

#...
invoice.organization = request.user.groups.first()
invoice.user_input = self.request.user.get_full_name()
invoice.price = form.cleaned_data['price'] #i update this field in UpdateView
invoice.quantity = form.cleaned_data['quantity']#i update this field in UpdateView

#this is what I do in form where I create my model I would like to do something like that in UpdateView too
if form.cleaned_data['price'] is not None and form.cleaned_data['quantity'] is not None:
     invoice.sum_price = float(form.cleaned_data['price']) * float(form.cleaned_data['quantity'])
else:
     invoice.sum_price = form.cleaned_data['price'] 
#...

This is how my UpdateView looks like: 这就是我的UpdateView的样子:

class InvoiceUpdate(LoginRequiredMixin, generic.UpdateView):
    login_url = '/accounts/login'
    redirect_field_name = 'redirect_to'

    success_url = '/'

    template_name = 'invoice/invoice_update.html'

    model = Invoice

    fields = [
        'number',
        'price',
        'quantity',
        'comment',
        'notes',
    ]

How can I know update fields in UpdateView class? 如何知道UpdateView类中的更新字段?

You can add this under your update view. 您可以在更新视图下添加此项。 It will updates the value for organization and user_input before saving to the database. 它将在保存到数据库之前更新organizationuser_input的值。

def form_valid(self, form):
    narocilnica = form.save(commit=False)
    narocilnica.organization = request.user.groups.first()
    narocilnica.user_input = self.request.user.get_full_name()
    if form.cleaned_data['price'] is not None and form.cleaned_data['quantity'] is not None:
        narocilnica.sum_price = float(form.cleaned_data['price']) * float(form.cleaned_data['quantity'])
    else:
        narocilnica.sum_price = form.cleaned_data['cena_brez_DDV'] 
    narocilnica = narocilnica.save()
    return self.success_url

Edit: Not sure what is cena_brez_DDV as it is not a field in the form, so you might get error for not having cleaned_data for that. 编辑:不确定什么是cena_brez_DDV因为它不是表单中的字段,因此您可能会因为没有cena_brez_DDV而收到错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM