Aula 65 – Loja Online – Resumo da Compra e Página de Sucesso

Aula 65 – Loja Online – Resumo da Compra e Página de Sucesso

Loja Online - Django - Resumo da Compra e Página de Sucesso

Loja Online – Django – Resumo da Compra e Página de Sucesso

Voltar para página principal do blog

Todas as aulas desse curso

Aula 64               Aula 66

Se gostarem do conteúdo dêem um joinha 👍 na página do Código Fluente no
Facebook

Esse é o link do código fluente no Pinterest

Meus links de afiliados:

Hostinger

Digital Ocean

One.com

Melhore seu NETWORKING

https://digitalinnovation.one/

Participe de comunidades de desenvolvedores:

Fiquem a vontade para me adicionar ao linkedin.

E também para me seguir no https://github.com/toticavalcanti.

Código final da aula:

https://github.com/toticavalcanti

Quer aprender python3 de graça e com certificado? Acesse então:

https://workover.com.br/python-codigo-fluente

Toti:

https://www.youtube.com/channel/UCUEtjLuDpcOvR3mIUr-viOA

Backing track / Play-along:

https://www.youtube.com/channel/UCT3TryVMqTqYBjf5g5WAHfA

Código Fluente

https://www.youtube.com/channel/UCgn-O-88XBAwdG9gUWkkb0w

Putz!

https://www.youtube.com/channel/UCZXop2-CECwyFYmHbhnAkAw

PIX para doações

PIX Nubank

PIX Nubank

Se quiser copiar o código do PIX:

00020126580014BR.GOV.BCB.PIX013643c5f950-535b-4658-b91f-1f1d135fe4105204000053039865802BR5925Antonio Cavalcante de Pau6009SAO PAULO61080540900062070503***6304946B


Aula 65 – Loja Online – Resumo da Compra e Página de Sucesso

Resumo da Compra e Página de Sucesso

Vamos começar alterar o checkout.html do carts para inserir os items do carrinho no resumo da compra, e também os endereços de envio e de cobrança.

django_ecommerce/e_commerce/carts/templates/carts/checkout.html 


{% extends "base.html" %}
{% block content %}
  {% 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>
      <div class='col-12 col-md-6'> 
        Continuar como Convidado
        {% 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>
   </div>
  {% else %}
  {% if not object.shipping_address %}
    <div class='row'>
      <div class='col-12'>
        <p class='lead'>Endereço de envio</p>
        <hr/>
      </div>
      <div class='col-6'>
        {% 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 class='col-6'>
        {% url 'checkout_address_reuse' as checkout_address_reuse %}
        {% include 'addresses/prev_addresses.html' with address_qs=address_qs next_url=request.build_absolute_uri address_type='shipping' action_url=checkout_address_reuse %}
      </div>
    </div>
  {% elif not object.billing_address %}
    <div class='row'>
      <div class='col-12'>
        <p class='lead'>Endereço de Cobrança</p>
        <hr/>
      </div>
      <div class='col-6'> 
        {% 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 class='col-6'>
        {% url 'checkout_address_reuse' as checkout_address_reuse %}
        {% include 'addresses/prev_addresses.html' with address_qs=address_qs next_url=request.build_absolute_uri address_type='billing' action_url=checkout_address_reuse %}
    </div>
  </div>
  {% else %}
    <h1>Finalizar Checkout</h1>
    <p>Items do Carrinho: {% for product in object.cart.products.all %}{{ product }}{% if not forloop.last %}, {% endif %}{% endfor %}</p>
    <p>Endereço de Envio: {{ object.shipping_address.get_address }}</p>
    <p>Endereço de Cobrança: {{ object.billing_address.get_address }}</p>
    <p>Total do Carrinho: {{ object.cart.total }}</p>
    <p>Total do Frete: {{ object.shipping_total }}</p>
    <p>Total do Pedido: {{ object.total }}</p>
    <form class='form' method='POST' action="">{% csrf_token %}
      <button type='submit' class='btn btn-success'>Checkout</button>
    </form>
  {% endif %}
  {% endif %}
{% endblock %}

Agora no models.py do addresses, vamos criar o método get_address().

django_ecommerce/e_commerce/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)
    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='United States of America')
    state           = models.CharField(max_length=120)
    postal_code     = models.CharField(max_length=120)

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

    def get_address(self):
        return "{line1}\n{line2}\n{city}\n{state}, {postal}\n{country}".format(
                line1 = self.address_line_1,
                line2 = self.address_line_2 or "",
                city = self.city,
                state = self.state,
                postal= self.postal_code,
                country = self.country
            )

Vamos fazer a função checkout_done_view.py que vai renderizar a página de sucesso.

django_ecommerce/e_commerce/carts/views.py 


from django.shortcuts import render, redirect

from accounts.forms import LoginForm, GuestForm
from accounts.models import GuestEmail

from addresses.forms import AddressForm
from addresses.models import Address

from billing.models import BillingProfile
from orders.models import Order
from products.models import Product
from .models import Cart

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):
    product_id = request.POST.get('product_id')
    if product_id is not None:
        try:
            product_obj = Product.objects.get(id=product_id)
        except Product.DoesNotExist:
            print("Mostrar mensagem ao usuário, esse produto acabou!")
            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) # cart_obj.products.add(product_id)
        request.session['cart_items'] = cart_obj.products.count()
        # return redirect(product_obj.get_absolute_url())
    return redirect("cart:home")

def checkout_home(request):
    #aqui a gente pega o carrinho
    cart_obj, cart_created = Cart.objects.new_or_get(request)
    order_obj = None
    #se o carrinho acabou de ser criado, ele tá zerado
    #ou se o carrinho já existir mas não tiver nada dentro
    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, billing_profile_created = BillingProfile.objects.new_or_get(request)
    address_qs = None
    if billing_profile is not None:
        if request.user.is_authenticated:
            address_qs = Address.objects.filter(billing_profile=billing_profile)
        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()
    if request.method == "POST":
        #verifica se o pedido foi feito
        is_done = order_obj.check_done()
        if is_done:
            order_obj.mark_paid()
            request.session['cart_items'] = 0
            del request.session['cart_id']
            return redirect("cart:success")
    context = {
        "object": order_obj,
        "billing_profile": billing_profile,
        "login_form": login_form,
        "guest_form": guest_form,
        "address_form": address_form,
        "address_qs": address_qs,
    }
    return render(request, "carts/checkout.html", context)

def checkout_done_view(request):
    return render(request, "carts/checkout-done.html", {})

Vamos criar a página de sucesso, o checkout-done.html, dentro do templates do carts.

django_ecommerce/e_commerce/carts/templates/carts/checkout-done.html


{% extends "base.html" %}
{% block content %}
<div class='col-6 mx-auto py-5 text-center'>
  <h1 class='display-1'>Obrigado pelo seu pedido!!!</h1>
</div>
{% endblock %}

Agora no urls.py do carts declare a rota.

django_ecommerce/e_commerce/carts/urls.py 


from django.urls import path

app_name = "carts"

from .views import (
                        cart_home, 
                        checkout_home,
                        cart_update,
                        checkout_done_view
                    )

urlpatterns = [
    path('', cart_home, name='home'),
    path('checkout/success/', checkout_done_view, name='success'),
    path('checkout/', checkout_home, name='checkout'),
    path('update/', cart_update, name='update')
]

É isso, ficamos por aqui e até a próxima. 😉

Voltar para página principal do blog

Todas as aulas desse curso

Aula 64               Aula 66

Código final da aula:

https://github.com/toticavalcanti

Outros canais

Toti:

https://www.youtube.com/channel/UCUEtjLuDpcOvR3mIUr-viOA

Backing track / Play-along:

https://www.youtube.com/channel/UCT3TryVMqTqYBjf5g5WAHfA

Código Fluente

https://www.youtube.com/channel/UCgn-O-88XBAwdG9gUWkkb0w

Putz!

https://www.youtube.com/channel/UCZXop2-CECwyFYmHbhnAkAw

Se gostarem do conteúdo dêem um joinha 👍 na página do Código Fluente no
Facebook

Esse é o link do código fluente no Pinterest

Meus links de afiliados:

Hostinger

Digital Ocean

One.com

Nos vemos na próxima então, \o/  😉 Bons Estudos!

About The Author
-

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>