我有以下表单,它在提交时会生成一个值错误。
/en/orders/create/ 处的 ValueError
视图 orders.views.order_create 没有返回 HttpResponse 对象。它返回 None 。
我的表格:
from django import forms
from .models import Order
from localflavor.us.forms import USZipCodeField
class OrderCreateForm(forms.ModelForm):
postal_code = USZipCodeField()
class Meta:
model = Order
fields = ['first_name', 'last_name', 'email', 'address',
'postal_code', 'city']
我的模型:
class Order(models.Model):
first_name = models.CharField(_('first name'), max_length=50)
last_name = models.CharField(_('last name'), max_length=50)
email = models.EmailField(_('e-mail'))
address = models.CharField(_('address'), max_length=250)
postal_code = models.CharField(_('postal code'), max_length=20)
city = models.CharField(_('city'), max_length=100)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
paid = models.BooleanField(default=False)
class Meta:
ordering = ('-created', )
def __str__(self):
return f'Order {self.id}'
我的观点:
def order_create(request):
if request.method == 'POST':
form = OrderCreateForm(request.POST)
if form.is_valid():
order.save()
request.session['order_id'] = order.id
# redirect for payment return
return redirect(reverse('payment:process'))
else:
form = OrderCreateForm()
return render(request,
'orders/order/create.html',
{'cart': cart, 'form': form})
追溯:
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/en/orders/create/
Django Version: 3.0.6
Python Version: 3.8.2
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rosetta',
'parler',
'localflavor',
'shop.apps.ShopConfig',
'cart.apps.CartConfig',
'orders.apps.OrdersConfig',
'payment.apps.PaymentConfig',
'coupons.apps.CouponsConfig']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback (most recent call last):
File "/home/[user]/.virtualenvs/shop/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/home/[user]/.virtualenvs/shop/lib/python3.8/site-packages/django/core/handlers/base.py", line 124, in _get_response
raise ValueError(
Exception Type: ValueError at /en/orders/create/
Exception Value: The view orders.views.order_create didn't return an HttpResponse object. It returned None instead.
该过程运行良好,并重定向到付款表单,表单中没有此行:postal_code = USZipCodeField()
我似乎无法理解导致错误的原因。
预期行为:
在有效表格上,重定向到付款。
在无效表单上,USZipCodeField 引发的验证错误:“输入格式为 XXXXX 或 XXXXX-XXXX 的邮政编码。”