Django UpdateView更新在视图中

时间:2017-09-20 09:30:41

标签: python django

我在django中制作简单的应用程序,我有一个UpdateView用于在数据库中更新我的模型。我更新表格我没有包括我想在后台更新其中一些字段的所有字段。 类似的东西:

import 'package:angular/angular.dart';
import 'package:angular_components/angular_components.dart';

@Component(
    selector: 'my-app',
    templateUrl: 'app_component.html',
    styleUrls: const [
    'app_component.css',
    'package:angular_components/src/components/app_layout/layout.scss.css'],
    directives: const [
      DeferredContentDirective,
      MaterialButtonComponent,
      MaterialIconComponent,
      MaterialPersistentDrawerDirective,
      MaterialToggleComponent,
      MaterialListComponent,
      MaterialListItemComponent,
    ],
    providers: const [materialProviders],
    )
class AppComponent {
  bool end = false;
}

这就是我的UpdateView的样子:

#...
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'] 
#...

如何知道UpdateView类中的更新字段?

1 个答案:

答案 0 :(得分:0)

您可以在更新视图下添加此项。在保存到数据库之前,它会更新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

编辑:不确定cena_brez_DDV是什么,因为它不是表单中的字段,因此您可能会因为没有clean_data而收到错误。