程序问答   发布时间:2022-06-01  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了点击提交账单地址表单会在登录时重定向我,而不是将我重定向到送货地址表单大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决点击提交账单地址表单会在登录时重定向我,而不是将我重定向到送货地址表单?

开发过程中遇到点击提交账单地址表单会在登录时重定向我,而不是将我重定向到送货地址表单的问题如何解决?下面主要结合日常开发的经验,给出你关于点击提交账单地址表单会在登录时重定向我,而不是将我重定向到送货地址表单的解决方法建议,希望对你解决点击提交账单地址表单会在登录时重定向我,而不是将我重定向到送货地址表单有所启发或帮助;

我正在学习解释如何使用 django 构建电子商务应用程序的教程。

我有一个购物车部分 [s1],客户可以在其中查看他/她在购物车中的产品的简历。
在这里,客户可以点击“结帐”按钮,根据教程,

如果客户已登录:

  • 应将他/她带到收货地址部分 [s2],他/她可以在此填写收货地址表单。

其他:

  • 应引导他/她进入访客身份验证部分 [s2-b] 在那里他/她可以继续作为访客(要求客户提交他/她的电子邮件地址)或登录(要求客户提交用户名和密码),然后到达收货地址表单部分 [s2]。

然后,应用应将客户引导至帐单地址表单 [s3],然后引导至完成部分 [s4]

我的问题是我无法通过送货地址部分 [s3],因为当我点击提交按钮时,应用程序会将我重定向到登录表单,(即使我已经登录也会发生这种情况)用户和密码文件都显示“此字段是必需的”消息,当我输入这些信息并按提交按钮时,应用程序将我返回到主页。所以我永远无法到达帐单地址表 [s4]。

我不明白出了什么问题,这是我的代码:

cartsbillingaddresses 是我的应用

carts/vIEws.py

from django.shortcuts import render,redirect       
from products.models import Product
from .models import Cart    
from orders.models import Order    
from accounts.forms import LoginForm    
from billing.models import BillingProfile    
from accounts.forms import GuestForm    
from accounts.models import Guestemail    
from addresses.forms import AddressForm    
from addresses.models import Address


def cart_home(request):    
    cart_obj,new_obj = Cart.objects.new_or_get(request)    
    return render(request,"carts/home.HTML",{"cart":cart_obj})


def cart_update(request):
    print(request.POST)
    product_ID = request.POST.get('product_ID',100) # il 2° arg è il default
    
    if product_ID is not None:
        try:
            product_obj = Product.objects.get(ID=product_ID)
        except Product.DoesNotExist:
            print("product is gone?")
            return redirect("cart:home")    
        
    
        cart_obj,new_obj = Cart.objects.new_or_get(request)
    
        if product_obj in cart_obj.products.all():
            cart_obj.products.remove(product_obj)
        else:
            cart_obj.products.add(product_obj)
        
        request.session['cart_items'] = cart_obj.products.count()

    return redirect("cart:home")


def checkout_home(request):
    cart_obj,cart_created = Cart.objects.new_or_get(request)
    order_obj = None

    if cart_created or cart_obj.products.count() == 0:
        return redirect("cart:home")    

    login_form = LoginForm()
    guest_form = GuestForm()
    address_form = AddressForm()
    billing_address_ID = request.session.get("billing_address_ID",None)
    shipPing_address_ID = request.session.get("shipPing_address_ID",None)

    billing_profile = BillingProfile.objects.new_or_get(request)


    if billing_profile is not None:
        order_obj,order_obj_created = Order.objects.new_or_get(billing_profile,cart_obj)
        
        if shipPing_address_ID:
            order_obj.shipPing_address = Address.objects.get(ID=shipPing_address_ID)
            del request.session["shipPing_address_ID"]

        if billing_address_ID:
            order_obj.billing_address = Address.objects.get(ID=billing_address_ID)
            del request.session["billing_address_ID"]

        if billing_address_ID or shipPing_address_ID:
            order_obj.save()

    context = {

        "object": order_obj,"billing_profile": billing_profile,"login_form": login_form,"guest_form" : guest_form,"address_form" : address_form,}

    return render(request,"carts/checkout.HTML",context )

addresses/vIEws.py

from django.shortcuts import render,redirect    
from .forms import AddressForm
from django.utils.http import is_safe_url    
from billing.models import BillingProfile  

def checkout_address_create_vIEw(request):

    form = AddressForm(request.POST or None)
    context = {"form":form}    

    next_ = request.GET.get('next')
    next_post = request.POST.get('next')
    redirect_path = next_ or next_post or None

    if form.is_valID():
        print("form is valID")
        print(request.POST)
        instance = form.save(commit=False)            

        billing_profile,billing_profile_created = BillingProfile.objects.new_or_get(request)

        if billing_profile is not None:
            address_type = request.POST.get('address_type','shipPing')
            instance.billing_profile = billing_profile
            instance.address_type = address_type
            instance.save()
            request.session[address_type +  "_address_ID"] = instance.ID
            print(address_type +  "_address_ID")

        else:
            print("error here smth")
            return redirect("cart:checkout")

        # redirect to success page
        if is_safe_url(redirect_path,request.get_host()):
            return redirect(redirect_path)
        else:
            return redirect("cart:checkout")

    print("form is not valID")

    return redirect("cart:checkout")

addresses/models.py

from django.db import models    
from billing.models import BillingProfile    


ADDRESS_TYPES = (

    ('billing',"billing"),('shipPing',"shipPing"),)


class Address(models.Model):
    billing_profile = models.ForeignKey(BillingProfile,on_delete=models.CASCADE)
    address_type = models.CharFIEld(max_length=120,choices=ADDRESS_TYPES)
    address_line_1 = models.CharFIEld(max_length=120)
    address_line_2 = models.CharFIEld(max_length=120,null=True,blank=True)
    city = models.CharFIEld(max_length=120)
    country = models.CharFIEld(max_length=120,default="Italy")
    state = models.CharFIEld(max_length=120)
    postal_code = models.CharFIEld(max_length=120)

    def __str__(self):
        return str(self.billing_profile)

billing/models.py

from django.db import models
from django.conf import settings    
# from python_ecommerce.utils import unique_order_ID_generator
from django.db.models.signals import pre_save,post_save    
from accounts.models import Guestemail    

User = settings.AUTH_USER_MODEL


class BillingProfileManager(models.Manager):
    def new_or_get(self,request):
        user=request.user
        guest_email_ID = request.session.get('guest_email_ID')
        created = False
        obj = None

        if user.is_authenticated:
            obj,created = self.model.objects.get_or_create(
                user=user,email=user.email
                )

        elif guest_email_ID is not None:
            guest_email_obj = Guestemail.objects.get(ID=guest_email_ID)
            obj,created = self.model.objects.get_or_create(
                email=guest_email_obj.email
                )

        else:
            print("nè guest nè user")

        return obj


class BillingProfile(models.Model):
    user = models.OnetoOneFIEld(User,blank=True,on_delete=models.CASCADE) #OnetoOneFIEld
    email = models.EmailFIEld()
    active = models.BooleanFIEld(default=True)
    update = models.DateTimeFIEld(auto_Now=True)
    timestamp = models.DateTimeFIEld(auto_Now_add=True)
    # customer is in stripe or brwwin

    objects = BillingProfileManager()

    def __str__(self):
        return self.email

def user_created_receiver(sender,instance,created,*args,**kwargs):
    if created and instance.email:
        BillingProfile.objects.get_or_create(user=instance,email=instance.email)

post_save.connect(user_created_receiver,sender=User)

python_ecommerce/urls.py

from django.contrib import admin
from django.urls import path,include
from .vIEws import home_page,about_page,contact_page
from django.conf import settings
from django.conf.urls.static import static
from django.vIEws.generic.base import TemplateVIEw
from carts.vIEws import cart_home
from accounts.vIEws import login_page,register_page
from django.contrib.auth.vIEws import logoutVIEw
from accounts.vIEws import guest_register_vIEw
from addresses.vIEws  import checkout_address_create_vIEw


urlpatterns = [
    path('admin/',admin.site.urls),path('',home_page,name="home"),path('about/',name="about"),path('contact/',contact_page,name="contact"),path('login/',login_page,name="login"),path('register/',register_page,name="register"),path('bootstrap/',TemplateVIEw.as_vIEw(template_name='bootstrap/example.HTML')),include("products.urls",namespace='products')),#spostato nell altro 
    path('',include("search.urls",namespace='search')),path('cart/',include("carts.urls",namespace="cart")),path("logout/",logoutVIEw.as_vIEw(),name="logout"),path('register/guest/',guest_register_vIEw,name="guest_register"),path('checkout/address/create/',checkout_address_create_vIEw,name='checkout_address_create_vIEw'),]

if settings.DEBUG:
    urlpatterns = urlpatterns + static(settings.STATIC_URL,document_root=settings.STATIC_ROOT)
    urlpatterns = urlpatterns + static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)

carts/templates/carts/checkout.HTML

{% extends "base.HTML" %}


{% block content %}

{{ object.order_ID }} &nbsp&nbsp {{ object.cart }}   



{% if not billing_profile %}
    <div class="row text-center">

        <div class='col-12 col-md-6'>
            <p class="lead">Login</p>
            {% include 'accounts/snippets/form.HTML' with form=login_form next_url=request.build_absolute_uri %}
        </div>

        <br><br><br>

        <div class='col-12 col-md-6'>
            continue as guest
            {% url 'guest_register' as guest_register_url %}
            {% include 'accounts/snippets/form.HTML' with form=guest_form next_url=request.build_absolute_uri action_url=guest_register_url %}   
        </div>

    <!-- qui è obbligatorio usare la struttura alias perchè non puoi mettere url tag dentro action_url= -->

    </div>

{% else %}

    {% if not object.shipPing_address %}

    <div class=row>
        <div class='col-md-6 mx-auto col-10'>
            <p class='lead'>ShipPing Address</p>

            <hr/>

            {% url 'checkout_address_create' as checkout_address_create %}
            {% include 'addresses/form.HTML' with form=address_form next_url=request.build_absolute_uri action_url=checkout_address_create address_type='shipPing' %}   

        </div>
    </div>
    
    {% elif not object.billing_address %}
    <div class=row>
        <div class='col-md-6 mx-auto col-10'>
            <p class='lead'>Billing Address</p>

            <hr/>

            {% url 'checkout_address_create' as checkout_address_create %}
            {% include 'addresses/form.HTML' with form=address_form next_url=request.build_absolute_uri action_url=checkout_address_create address_type='billing' %}   

        </div>
    </div>

    {% else %}

        <h1>Finalize checkout</h1>

        <p>Cart total: {{ object.cart.total }}</p>
        <p>ShipPing total: {{ object.shipPing_total }}</p>
        <p>Order total: {{ object.total }}</p>
        <button>Checkout</button>

    {% endif %}

{% endif %}


{% endblock %}

解决方法

已解决

python_ecommerce/urls.py 中有一个非常简单的错误:

urlspattern中,我将视图checkout_address_create_view命名为checkout_address_create_view,而在模板中我将其称为checkout_address_create,因此模板找不到该函数,因此不会知道为什么让我回到登录表单。

我替换了

path('checkout/address/create/',checkout_address_create_view,name='checkout_address_create_view'),

path('checkout/address/create/',

这解决了那个错误。

大佬总结

以上是大佬教程为你收集整理的点击提交账单地址表单会在登录时重定向我,而不是将我重定向到送货地址表单全部内容,希望文章能够帮你解决点击提交账单地址表单会在登录时重定向我,而不是将我重定向到送货地址表单所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: