如何在验证之前覆盖字段值?

时间:2010-10-13 21:26:23

标签: django django-forms

我有一个表单,我需要在验证之前设置一些值。我在尝试:

if request.method == 'POST':
    reservation_form = ReservationForm(request.POST, initial={'is_reservation':True, 'user':request.user})

但它不起作用。如果我从(模型)表单中排除'user'字段,我会得到一个空约束错误,如果我包含它,我会得到一个验证错误。因此,它要么忽略了初始值,因为我已经排除了字段,要么请求.POST数据胜过它,即使没有发布该值也是如此。

那么我该怎么做呢?


class ReservationForm(ModelForm): # TODO: abstract this and shipment form
    service_types = MultipleChoiceField(widget=MultiColumnCheckboxSelect(columns=2), choices=ServiceTypes,
    initial=[ServiceTypes.OPEN_TRANS], error_messages={'required': 'Please select at least one service type.'})
    payment_methods = MultipleChoiceField(widget=MultiColumnCheckboxSelect(columns=2), choices=PaymentMethods,
    error_messages={'required': 'Please select at least one payment method.'})
    payment_times = MultipleChoiceField(widget=MultiColumnCheckboxSelect(columns=2), choices=PaymentTimes, required=True,
    error_messages={'required': 'Please select at least one payment type.'})

    class Meta:
    model = Shipment
    exclude = ['headline', 'created', 'updated', 'expiry_date', 'status', 'accepted_bid', 'pickup_address', 'dropoff_address', 'billing_address', 'target_price']
    widgets = {
        'pickup_earliest': TextInput(attrs={'class':'date'}),
        'pickup_latest': TextInput(attrs={'class':'date'}),
        'dropoff_earliest': TextInput(attrs={'class':'date'}),
        'dropoff_latest': TextInput(attrs={'class':'date'}),
        'additional_info': WarningTextArea,
    }

1 个答案:

答案 0 :(得分:1)

好的,我希望我现在能够正确理解这个问题:

您的ReservationForm没有user且没有is_reservation字段。因此,设置initial={'user': ...}没有任何意义,因为user不是该表单的一部分(is_reservation也不是。)

另一方面,您有一个Reservation模型,该模型是从表单的某些值和其他用户ID填充的,以及is_reservation布尔值。

所以,通常你会这样写:

form = ReservationForm() # you migth want to set inital values here
if request.method == 'POST':
    form = ReservationForm(request.POST)
    if form.is_valid():
        data = form.cleaned_data
        reservation = Reservation() # create a new model

        # copy the values from the form to your new model
        reservation.payment_method = data['payment_methods']
        reservation.payment_time = data['payment_time']

        # set some additional values for the model (which are required)
        reservation.user_id = request.session['user_id'] # for example
        reservation.is_reservation = True

        # save the reservation (all required fields, including the user_id are now set)
        reservation.save()

请注意,这只是一个例子。我还没有看过你的模型类,所以你的模型可能看起来有点不同。但我认为你将能够适应它。

<强>更新

我认为以下内容可能有效(但您必须排除正如您所提到的useris_reservation)。

form = ReservationForm(request.POST)
reservation = form.save(commit=False)
reservation.user = request.user
reservation.is_reservation = True
reservation.save()