表单未将书面地址保存到数据库

时间:2020-02-12 10:11:01

标签: django django-views

在Django中,我想构建一个表单来收集用户的送货地址!然后将它们保存到数据库 views.py从定义函数“ is_valid_form(values)”开始

    def is_valid_form(values):
    valid = True
    for field in values:
        if field == '':
            valid = False
    return valid


class EnCheckoutView(View):
    def get(self, *args, **kwargs):
        try:
            order = Order.objects.get(user=self.request.user, ordered=False)
            form = CheckoutForm()
            context = {
                'form': form,
                'couponform': CouponForm(),
                'order': order,
                'DISPLAY_COUPON_FORM': True
            }
            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]
                })
            return render(self.request, 'en-checkout-page.html', context)
        except ObjectDoesNotExist:
            messages.info(self.request, 'You do not have an active order.')
            return redirect('core:en-checkout')

    def post(self, *args, **kwargs):

        try:
            order = Order.objects.get(user=self.request.user, ordered=False)

        except ObjectDoesNotExist:
            messages.warning(self.request, 'You do not have an active order')
            return redirect('core:en-order-summary')

        form = CheckoutForm(self.request.POST or None)
        if form.is_valid():
            use_default_shipping = form.cleaned_data.get("use_default_shipping")
            if use_default_shipping:
                print('Using the default shipping address')
                address_qs = Address.objects.filter(user=self.request.user, default=True)
                if address_qs.exists():
                    shipping_address = address_qs[0]
                    order.shipping_address = shipping_address
                    order.save()
                else:
                    messages.info(self.request, 'No default shipping address available')
                    return redirect('core:en-checkout')
            else:
                print('User is entering a new shipping address')
                customer_name = form.cleaned_data.get('customer_name')
                phone = form.cleaned_data.get('phone')
                email = form.cleaned_data.get('email')
                shipping_address1 = form.cleaned_data.get('shipping_address1')
                shipping_address2 = form.cleaned_data.get('shipping_address2')
                en_shipping_country = form.cleaned_data.get('en_shipping_country')
                shipping_zip = form.cleaned_data.get("shipping_zip")
                if is_valid_form([customer_name, phone, shipping_address1]):
                    shipping_address = Address(
                        user=self.request.user,
                        customer_name=customer_name,
                        phone=phone,
                        email=email,
                        street_address=shipping_address1,
                        apartment_address=shipping_address2,
                        country=en_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, 'Please ***fill in the required shipping address fields')

        en_payment_option = form.cleaned_data.get('en_payment_option')

        if en_payment_option == 'S':
            return redirect('core:en-payment', en_payment_option='Pay with credit card')
        elif en_payment_option == 'P':
            return redirect('core:ar-delivery', en_payment_option='Cash on delivery')
        else:
            messages.warning(self.request, 'Invalid payment option selected')
            return redirect('core:en/checkout')

为什么此表单不将地址保存到数据库? 我本可以发布forms.py,html模板和models.py,但我想这将解释问题。

forms.py

EN_PAYMENT_CHOICES = (
    ('S', 'Pay with credit card'),
    ('P', 'Cash on delivery')
)


class CheckoutForm(forms.Form):
    customer_name = forms.CharField(max_length=100, required=True)
    phone = forms.IntegerField(required=True)
    email = forms.EmailField()
    shipping_address1 = forms.CharField(required=True)
    shipping_address2 = forms.CharField(required=False)
    ar_shipping_country = CountryField(blank_label='(اختار البلد)').formfield(
        required=False,
        widget=CountrySelectWidget(attrs={
            'class': 'custom-select d-block w-100',
        }))
    en_shipping_country = CountryField(blank_label='(Choose a country)').formfield(
        required=False,
        widget=CountrySelectWidget(attrs={
            'class': 'custom-select d-block w-100',
        }))
    shipping_zip = forms.CharField(required=False)

    set_default_shipping = forms.BooleanField(required=False)
    use_default_shipping = forms.BooleanField(required=False)

    payment_option = forms.ChoiceField(
        widget=forms.RadioSelect, choices=PAYMENT_CHOICES)

    en_payment_option = forms.ChoiceField(
        widget=forms.RadioSelect, choices=EN_PAYMENT_CHOICES)

models.py

class Address(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    customer_name = models.CharField(max_length=100, null=True)
    phone = models.IntegerField(null=True)
    email = models.EmailField(null=True)
    street_address = models.CharField(max_length=250)
    apartment_address = models.CharField(max_length=250)
    country = CountryField(multiple=False, null=True)
    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

    class Meta:
        verbose_name_plural = 'Addresses'

0 个答案:

没有答案