UnboundLocalError в / checkoutview /. локальная переменная shipping_address, на которую ссылается перед назначением - PullRequest
0 голосов
/ 02 августа 2020

У меня возникла ошибка «UnboundLocalError в / checkoutview /. Локальная переменная 'shipping_address' указана перед назначением. Пожалуйста, помогите мне разобраться.

Я получил из трассировки, что проблема выделена жирным шрифтом - ** billing_address = shipping_address **

обновлено: я только что включил трассировку


Traceback (most recent call last):
  File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
    response = get_response(request)
  File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\views\generic\base.py", line 71, in view
    return self.dispatch(request, *args, **kwargs)
  File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\views\generic\base.py", line 97, in dispatch
    return handler(request, *args, **kwargs)
  File "C:\Users\Lenovo\decommerce\websites\views.py", line 267, in post
    billing_address = shipping_address

Exception Type: UnboundLocalError at /checkoutview/
Exception Value: local variable 'shipping_address' referenced before assignment

views.py


class CheckoutView(View):
    def get(self, *args, **kwargs):
        try:
            order = Order.objects.get(
                user=self.request.user,
                ordered=False,
            )
            form = CheckoutForm()
            context = {
                "order": order,
                "form": form
            }
            shipping_address_qs = Address.objects.filter(
                user=self.request.user,
                address_type="S",
                default=True
            )
            if shipping_address_qs.exists():
                context.update(
                    {"default_shipping_address": shipping_address_qs[0]}
                )
            billing_address_qs = Address.objects.filter(
                user=self.request.user,
                address_type="B",
                default=True
            )
            if billing_address_qs.exists():
                context.update(
                    {"default_billing_address": billing_address_qs[0]}
                )
            return render(self.request, "checkout-page.html", context)
        except ObjectDoesNotExist:
            messages.info(
                self.request, f"There exist no default shipping information")
            return redirect("checkout")

    def post(self, *args, **kwargs):
        form = CheckoutForm(self.request.POST or None)
        try:
            order = Order.objects.get(
                user=self.request.user,
                ordered=False,
            )
            if form.is_valid():
                use_default_shipping = form.cleaned_data.get(
                    "use_default_shipping")
                if use_default_shipping:
                    address_qs = Address.objects.filter(
                        user=self.request.user,
                        address_type="S",
                        default=True
                    )
                    if address_qs.exists():
                        shipping_address = address_qs[0]
                        order.shipping_address = shipping_address
                        order.save()

                    else:
                        messages.info(
                            self.request, f"There exist no default shipping information")
                        return redirect('checkout')
                else:
                    messages.info(
                        self.request, f"In the absence of default shipping information, new data would be used")
                    shipping_address1 = form.cleaned_data.get(
                        "shipping_address")
                    shipping_address2 = form.cleaned_data.get(
                        "shipping_address2")
                    shipping_country = form.cleaned_data.get(
                        "shipping_country")
                    shipping_zip = form.cleaned_data.get("shipping_zip")

                    if is_valid_form([shipping_address1, shipping_country, shipping_zip]):
                        shipping_address = Address(
                            user=self.request.user,
                            street_address=shipping_address1,
                            apartment_address=shipping_address2,
                            countries=shipping_country,
                            zip=shipping_zip,
                            address_type="S",
                        )
                        shipping_address.save()
                        order.shipping_address = shipping_address
                        order.save()

                        set_default_shipping = form.cleaned_data.get(
                            "set_default_shipping")
                        if set_default_shipping:
                            shipping_address.default = True
                            shipping_address.save()

                    else:
                        messages.info(
                            self.request, f"forms or data entered arent valid")

                use_default_billing = form.cleaned_data.get(
                    "use_default_billing")
                same_billing_address = form.cleaned_data.get(
                    "same_billing_address")

                if same_billing_address:
  >>>>>>>>>>>>>>>>>>**billing_address = shipping_address**<<<<<<<<<<<<<<<<<<<<<<<<<<<<
                    billing_address.pk = None
                    billing_address.save()
                    billing_address.address_type = "B"
                    billing_address.save()
                    order.billing_address = billing_address
                    order.save()

                elif use_default_billing:
                    address_qs = Address.objects.filter(user=self.request.user,
                                                        address_type="B",
                                                        default=True
                                                        )

                    if address_qs.exists():
                        billing_address = address_qs[0]
                        order.billing_address = billing_address
                        order.save()

                    else:
                        messages.info(
                            self.request, f"There exist no default billing information")
                        return redirect("checkout")
                else:
                    messages.info(
                        self.request, f"In the absence of default billing information, new data would be used")
                    billing_address1 = form.cleaned_data.get("billing_address")
                    billing_address2 = form.cleaned_data.get(
                        "billing_address2")
                    billing_country = form.cleaned_data.get("billing_country")
                    billing_zip = form.cleaned_data.get("billing_zip")
                    if is_valid_form([billing_address1, billing_country, billing_zip]):
                        billing_address = Address(
                            user=self.request.user,
                            street_address=billing_address1,
                            apartment_address=billing_address2,
                            countries=billing_country,
                            zip=billing_zip,
                            address_type="B",
                        )
                        billing_address.save()
                        order.billing_address = billing_address
                        order.save()

                        set_default_billing = form.cleaned_data.get(
                            "set_default_billing")

                        if set_default_billing:
                            billing_address.default = True
                            billing_address.save()
                            order.billing_address = billing_address
                            order.save()
                    else:
                        messages.info(
                            self.request, f"There exist no default billing information")

                payment_option = form.cleaned_data.get("payment_option")
                if payment_option == "S":
                    return redirect("payment", payment_option="Stripe")
                elif payment_option == "P":
                    return redirect("payment", payment_option="paypal")
                else:
                    messages.info(
                        self.request, f"Please select a valid payment option")
                    return redirect("checkout")
        except ObjectDoesNotExist:
            messages.info(
                self.request, f"Please select a valid payment option")
            return redirect("order-summary")


Пожалуйста, помогите мне исправить эту ошибку. Я новичок от ie до Django, и я застрял из-за этой ошибки.

часть models.py

class Address(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL,
                             on_delete=models.CASCADE)
    street_address =  models.CharField(max_length=100)                        
    apartment_address = models.CharField(max_length=100)
    countries = CountryField(multiple=False)
    zip = models.CharField(max_length=100)
    address_type = models.CharField(max_length=1, choices=ADDRESS_CHOICES)
    default = models.BooleanField(default=False)
    

    def __str__(self):
        return self.user.username

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...