我正在尝试在一个视图中处理三种形式。我解释 : 这是一个结帐表单,其中包含用于发送地址,帐单地址,信用卡信息的表单。
我的问题是,我想让用户选择是否结算地址与发货地址相同。我用一个复选框做了这个。
但是由于这三种形式,我现在仍然坚持验证。我不知道如何处理它们。
这是我的代码:
def show_checkout(request, template_name='checkout/checkout.html'):
user = User.objects.filter(pk=request.user.id)
if request.method == 'POST':
form = CheckoutForm(request.POST)
form_adress = ShippingForm(request.POST)
if form.is_valid() and form_adress.is_valid():
response = process(request)
form_adress.save(commit=False)
if not form_adress.same_adress:
form_adress.user_shipping = user
form_adress.user_billing = user
else:
form_adress.user_shipping = user
form_billing = BillingForm(request.POST)
form_billing.save(commit=False)
form_billing.user_billing = user
form_billing.save()
form_adress.save()
order_number = response.get('order_number', 0)
error_message = response.get('message', '')
if order_number:
request.session['order_number'] = order_number
receipt_url = urlresolvers.reverse('checkout_receipt')
return HttpResponseRedirect(receipt_url)
else:
error_message = 'Correct the errors below'
else:
form = CheckoutForm()
form_adress = ShippingForm()
form_billing = BillingForm()
error_message = None
if cart.is_empty(request):
cart_url = urlresolvers.reverse('show_cart')
return HttpResponseRedirect(cart_url)
page_title = 'Checkout'
return render(request, template_name, {
'error_message': error_message,
'page_title': page_title,
'form': form,
'form_adress': form_adress,
'form_billing': form_billing,
},
context_instance=RequestContext(request))
我的模板:
<form action="." method="post" class="row-fluid">
{% csrf_token %}
<div class="adress span10">
<fieldset class="checkout" style="float:left;">
<legend>Shipping Info</legend>
{{ form_adress.as_p }}
</fieldset>
<fieldset class="checkout billing_adress" style="float:left;">
<legend>Billing Info</legend>
{{ form_billing.as_p }}
</fieldset>
</div>
<fieldset class="checkout row-fluid">
<legend>Credit Card Info</legend>
<table>
{% form_table_row form.name %}
{% form_table_row form.lastname %}
{% form_table_row form.credit_card_number %}
{% form_table_row form.credit_card_type %}
{% form_table_row form.credit_card_expire_month %}
{% form_table_row form.credit_card_expire_year %}
{% form_table_row form.credit_card_cvv %}
</table>
</fieldset>
<table>
<tr>
<th colspan="2"><input type="submit" value="Place Order" class="submit" /></th>
</tr>
</table>
</form>
和我的表格:
class ShippingForm(forms.ModelForm):
same_adress = forms.BooleanField(required=True, label="different address for billing ?")
class Meta:
model = Address
exclude = 'user_billing, user_shipping'
class BillingForm(forms.ModelForm):
class Meta:
model = Address
exclude = 'user_billing, user_shipping'
目前我正面临分配前引用的局部变量'form_billing'
有什么建议吗?
提前谢谢!
答案 0 :(得分:1)
当form_billing
有效且form_adress
为false且form_adress.same_adress
为0时,您尚未初始化order_number
。
您在上下文中将其引用到render()
。
此外,如果
,看起来像这样if not form_adress.same_adress:
应该是
if form_adress.same_adress: