0

我有以下表单,它在提交时会生成一个值错误。

/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 的邮政编码。”

4

1 回答 1

1

我认为问题在于在表单无效的情况下代码不会呈现表单。对于无效的表单,该函数返回None的正是您所看到的错误消息。也许您提交的是空值或无效值?试试这个修改过的(未经测试的)版本:

def order_create(request):
    if request.method == 'POST':
        form = OrderCreateForm(request.POST)

        if form.is_valid():
            order = form.save()

            request.session['order_id'] = order.id

            # redirect for payment return
            return redirect(reverse('payment:process'))

    else:
        form = OrderCreateForm()

    # FIXME Where does 'cart' come from?
    return render(request,
                  'orders/order/create.html',
                  {'cart': cart, 'form': form})

这行得通吗?

您可能需要考虑使用内置CreateView以避免样板表单处理代码: https ://docs.djangoproject.com/en/3.0/ref/class-based-views/flattened-index/#CreateView

如果您还没有使用过基于类的视图,那么绝对值得研究一下。我发现我可以使用它们更快地移动,但它们确实需要一些时间来学习,并且当事情不工作时使流程更难遵循。以下是基于类的视图的完整文档: https ://docs.djangoproject.com/en/3.0/topics/class-based-views/

于 2020-05-30T20:51:50.940 回答