【问题标题】:How to fix django-oscar shipping UnboundLocalError?如何修复 django-oscar shipping UnboundLocalError?
【发布时间】:2019-04-09 22:04:38
【问题描述】:

我想向 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'))

【问题讨论】:

  • 请发布完整的堆栈跟踪。
  • 您将同一变量 methods 重用为全局变量和 repository.Repository.get_available_shipping_methods 内的局部变量。您应该为返回变量使用不同的变量名或使用as 导入。您看到的错误是因为导入的 methods 模块被重新分配为 tuple

标签: django django-oscar


【解决方案1】:

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

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

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

foo 执行时,foo 无法使用 x。所以稍微改变导入以避免这种情况;

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

【讨论】:

  • 这是非常好的解决方案。非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-24
  • 2021-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多