Django:UpdateView如何更改ModelForm中排除的字段的值?

时间:2019-02-06 10:01:29

标签: django django-models django-forms django-templates django-views

在这里,我有一个乘车要求班,它有原始乘客人数和总乘客人数。我允许用户使用ModelForm更改原始乘客编号的值,并且在UpdateView中,我希望使总乘客数量等于刚从ModelForm接收到的原始乘客数量。像这样: ModelForm

class RequestOwnerForm(ModelForm):
    class Meta:
        model = OwnerRequest
        fields = [

            'passenger_num',


        labels = {

            'passenger_num': 'How many passengers do you have?',

        }

UpdateView

class OwnerRequestEditView(LoginRequiredMixin, generic.UpdateView):

    model = OwnerRequest
    template_name = 'ride/request_edit.html'
    form_class = RequestOwnerForm
    success_url = reverse_lazy('ride:view_requests')

    def form_invalid(self, form):
        print("form is invalid")
        return HttpResponse("form is invalid.. this is just an HttpResponse object")

    def form_valid(self, form):
        pk = self.kwargs.get('pk')
        request = get_object_or_404(OwnerRequest, pk=pk)
        if request.status == 'open':
            request.passenger_num = form.cleaned_data['passenger_num']
            passenger_num = form.cleaned_data['passenger_num']
            request.total_passenger = passenger_num # I want total_passenger equals to passenger_num
            request.save()
            return super().form_valid(form)

但事实是total_passenger不会改变。

有人可以帮我吗?谢谢!

1 个答案:

答案 0 :(得分:1)

您要更新数字,然后调用super来保存表格,该表格会覆盖您刚才用原始表格保存的值。

我不确定为什么要两个具有相同值的字段,但是需要在已由视图获取的实例上进行设置。您应该让视图本身更新其他字段并保存。

def form_valid(self, form):
    if request.status == 'open':
        form.instance.total_passenger = form.cleaned_data['passenger_num']
    return super().form_valid(form)