Aula 64 – Loja Online – Selecionando o Endereço

Aula 64 – Loja Online – Selecionando o Endereço

Loja Online - Django - Selecionando o Endereço

Loja Online – Django – Selecionando o Endereço

Voltar para página principal do blog

Todas as aulas desse curso

Aula 63               Aula 65

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

Aula 64 – Loja Online – Selecionando o Endereço

Seleção do endereço

Vamos oferecer ao usuário a possibilidade dele escolher um endereço já cadastrado ao invés de ter que digitar toda vez.

Para começar vamos mudar o views.py do carts.

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)

Agora vamos alterar o checkout.html do carts.

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>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'>Checkout</button>
    </form>
  {% endif %}
  {% endif %}
{% endblock %}

Crie o prev_addresses.html com o conteúdo abaixo.

django_ecommerce/e_commerce/addresses/templates/addresses/prev_addresses.html 


{% if address_qs.exists %}
  <form method='POST' action='{{ action_url }}'> {% csrf_token %}
    {% if next_url %}
    <input type='hidden' name='next' value='{{ next_url }}' />
    {% endif %}
    {% if address_type %}
    <input type='hidden' name='address_type' value='{{ address_type }}' />
    {% endif %}
    {% for address in address_qs %}
      <label for='address-{{ address.id }}'>
        <input id='address-{{ address.id }}' type='radio' name='shipping_address' value='{{ address.id }}' />
      {{ address.address_line_1 }}
      </label><br/>
    {% endfor %}
  <button type='submit' class='btn btn-success'>Use Address</button>
  </form>
{% endif %}

Agora no views.py do addresses.

django_ecommerce/e_commerce/addresses/views.py  


from django.shortcuts import render, redirect
from django.utils.http import url_has_allowed_host_and_scheme

from billing.models import BillingProfile
from .forms import AddressForm
from .models import Address
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(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")
            return redirect("cart:checkout")

        if url_has_allowed_host_and_scheme(redirect_path, request.get_host()):
            return redirect(redirect_path)
        //else:
            //return redirect("cart:checkout")
    return redirect("cart:checkout") 

def checkout_address_reuse_view(request):
    if request.user.is_authenticated:
        context = {}
        next_ = request.GET.get('next')
        next_post = request.POST.get('next')
        redirect_path = next_ or next_post or None
        if request.method == "POST":
            print(request.POST)
            shipping_address = request.POST.get('shipping_address', None)
            address_type = request.POST.get('address_type', 'shipping')
            billing_profile, billing_profile_created = BillingProfile.objects.new_or_get(request)
            if shipping_address is not None:
                qs = Address.objects.filter(billing_profile=billing_profile, id=shipping_address)
                if qs.exists():
                    request.session[address_type + "_address_id"] = shipping_address
                if url_has_allowed_host_and_scheme(redirect_path, request.get_host()):
                    return redirect(redirect_path)
    return redirect("cart:checkout")

Agora no urls.py do e_commerce:

django_ecommerce/e_commerce/e_commerce/urls.py


from django.conf import settings
from django.conf.urls.static import static

from django.contrib import admin
from django.contrib.auth.views import LogoutView 
from django.urls import path, include
from django.views.generic import TemplateView
from carts.views import cart_home
from accounts.views import login_page, register_page, logout_page, guest_register_view
from addresses.views import checkout_address_create_view, checkout_address_reuse_view
from .views import (home_page,  
                    about_page, 
                    contact_page
)

urlpatterns = [
    path('', home_page, name='home'),
    path('about/', about_page, name='about'),
    path('contact/', contact_page, name='contact'),
    path('cart/', include("carts.urls", namespace="cart")),
    path('checkout/address/create/', checkout_address_create_view, name='checkout_address_create'),
    path('checkout/address/reuse/', checkout_address_reuse_view, name='checkout_address_reuse'),
    path('login/', login_page, name='login'),
    path('register/guest/', guest_register_view, name='guest_register'),
    path('logout/', LogoutView.as_view(), name='logout'),
    path('register/', register_page, name='register'),
    path('bootstrap/', TemplateView.as_view(template_name='bootstrap/example.html')),
    path('search/', include("search.urls", namespace="search")),
    path('products/', include("products.urls", namespace="products")),
    path('admin/', admin.site.urls),
]

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)

Na próxima aula a gente vai trabalhar na parte de resumo da compra, vamos colocar os endereços escolhidos no resumo da compra e fazer a página de sucesso da compra.

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

Voltar para página principal do blog

Todas as aulas desse curso

Aula 63               Aula 65

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>