django - 如何修复 django-oscar 运输 UnboundLocalError?

标签 django django-oscar

我想向 django-oscar 添加运输方法,但即使我已完成文档页面上的所有操作,我仍收到 UnboundLocalError 错误。

Request Method: GET
Request URL:    http://127.0.0.1:8000/checkout/shipping-address/
Django Version: 2.1.7
Exception Type: UnboundLocalError
Exception Value:    
local variable 'methods' referenced before assignment

repository.py

from oscar.apps.shipping import repository
from . import methods

class Repository(repository.Repository):

    def get_available_shipping_methods(self, basket, user=None, shipping_addr=None, request=None, **kwargs):
        methods = (methods.Standard(),)
        if shipping_addr and shipping_addr.country.code == 'GB':
            # Express is only available in the UK
            methods = (methods.Standard(), methods.Express())
        return methods

methods.py

from oscar.apps.shipping import methods
from oscar.core import prices
from decimal import Decimal as D

class Standard(methods.Base):
    code = 'standard'
    name = 'Shipping (Standard)'

    def calculate(self, basket):
        return prices.Price(
            currency=basket.currency,
            excl_tax=D('5.00'), incl_tax=D('5.00'))

class Express(methods.Base):
    code = 'express'
    name = 'Shipping (Express)'

    def calculate(self, basket):
        return prices.Price(
            currency=basket.currency,
            excl_tax=D('4.00'), incl_tax=D('4.00'))

最佳答案

我可以在文档中看到这一点,但他们看起来有一个错误。

使用UnboundLocalError,您实际上是在查看范围问题。一个非常简单的例子是;

x = 10
def foo():
    x += 1
    print x
foo()

foo执行时,x对foo不可用。因此,稍微更改导入以避免这种情况;

from oscar.apps.shipping import repository
from . import methods as shipping_methods

class Repository(repository.Repository):

    def get_available_shipping_methods(self, basket, user=None, shipping_addr=None, request=None, **kwargs):
        methods = (shipping_methods.Standard(),)
        if shipping_addr and shipping_addr.country.code == 'GB':
            # Express is only available in the UK
            methods = (shipping_methods.Standard(), shipping_methods.Express())
        return methods

关于django - 如何修复 django-oscar 运输 UnboundLocalError?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55601989/

相关文章:

python - 以编程方式在 Django Oscar 中创建规范的 "parent"产品

django oscar send_email 结果出现 ValueError : EMAIL_USE_TLS/EMAIL_USE_SSL are mutually exclusive,

python - IOError - 解码器 jpeg 不可用 - 即使在安装 libjpeg-dev n PIL 之后也是如此

python - Django.core.exceptions.ImproperlyConfigured : Error running functional_tests. py

javascript - 具有 ajax 请求和 python 交互的 Google 应用引擎

python - Django 管理员将上下文添加到index.html

python - djangorest框架多个url参数

python - 如何以编程方式在 django oscar 中添加产品图片?

python - 如何在 Django 中更改发件人电子邮件名称

python - Django 用户密码的 max_length 是多少?