Aula 57 – Loja Online – Django – Perfil de Convidado
Aula 57 – Loja Online – Django – Perfil de Convidado
Voltar para página principal do blog
Todas as aulas desse curso
Aula 56 Aula 58
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 57 – Loja Online – Django – Guest Checkout Profile
Construindo o Form de Login/Logout do usuário convidado
Vamos colocar no Accounts, porque faz mais sentido, já que podemos associar um User a outro tipo de Account no futuro.
Então vamos modificar o forms.py do accounts.
django_ecommerce/e_commerce/accounts/forms.py
from django import forms
from django.contrib.auth import get_user_model
User = get_user_model()
class GuestForm(forms.Form):
email = forms.EmailField()
class LoginForm(forms.Form):
username = forms.CharField()
password = forms.CharField(widget=forms.PasswordInput)
class RegisterForm(forms.Form):
username = forms.CharField()
email = forms.EmailField()
password = forms.CharField(widget=forms.PasswordInput)
password2 = forms.CharField(label='Confirm password', widget=forms.PasswordInput)
def clean_username(self):
username = self.cleaned_data.get('username')
qs = User.objects.filter(username=username)
if qs.exists():
raise forms.ValidationError("Esse usuário já existe, escolha outro nome.")
return username
def clean_email(self):
email = self.cleaned_data.get('email')
qs = User.objects.filter(email=email)
if qs.exists():
raise forms.ValidationError("Esse email já existe, tente outro!")
return email
def clean(self):
data = self.cleaned_data
password = self.cleaned_data.get('password')
password2 = self.cleaned_data.get('password2')
if password != password2:
raise forms.ValidationError("As senhas informadas devem ser iguais!")
return data
E no views.py do carts, vamos importar o form.
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 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):
print(request.POST)
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)
request.session['cart_items'] = cart_obj.products.count()
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")
#aqui a order associada ao carrinho
else:
order_obj, new_order_obj = Order.objects.get_or_create(cart = cart_obj)
user = request.user
billing_profile = None
login_form = LoginForm()
guest_form = GuestForm()
guest_email_id = request.session.get('guest_email_id')
if user.is_authenticated:
billing_profile, billing_profile_created = BillingProfile.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)
billing_profile, billing_guest_profile_created = BillingProfile.objects.get_or_create(
email=guest_email_obj.email)
else:
pass
context = {
"object": order_obj,
"billing_profile": billing_profile,
"login_form": login_form,
"guest_form": guest_form
}
return render(request, "carts/checkout.html", context)
Agora abra o views.py do accounts e faça as seguintes modificações.
django_ecommerce/e_commerce/accounts/views.py
from django.contrib.auth import authenticate, login, logout, get_user_model
from django.http import HttpResponse
from django.shortcuts import render,redirect
from django.utils.http import url_has_allowed_host_and_scheme
from .forms import LoginForm, RegisterForm, GuestForm
from .models import GuestEmail
def guest_register_view(request):
form = GuestForm(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():
email = form.cleaned_data.get("email")
new_guest_email = GuestEmail.objects.create(email = email)
request.session['guest_email_id'] = new_guest_email.id
if url_has_allowed_host_and_scheme(redirect_path, request.get_host()):
return redirect(redirect_path)
else:
return redirect("/register/")
return redirect("/register/")
def login_page(request):
form = LoginForm(request.POST or None)
context = {
"form": form
}
print("User logged in")
print(request.user.is_authenticated)
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.cleaned_data)
username = form.cleaned_data.get("username")
password = form.cleaned_data.get("password")
user = authenticate(request, username=username, password=password)
print(user)
print(request.user.is_authenticated)
if user is not None:
print(request.user.is_authenticated)
login(request, user)
if url_has_allowed_host_and_scheme( redirect_path, request.get_host() ):
return redirect( redirect_path )
else:
# Redireciona para uma página de sucesso.
return redirect("/")
else:
#Retorna uma mensagem de erro de 'invalid login'.
print("Login inválido")
return render(request, "accounts/login.html", context)
def logout_page(request):
context = {
"content": "Você efetuou o logout com sucesso! :)"
}
logout(request)
return render(request, "accounts/logout.html", context)
User = get_user_model()
def register_page(request):
form = RegisterForm(request.POST or None)
context = {
"form": form
}
if form.is_valid():
print(form.cleaned_data)
username = form.cleaned_data.get("username")
email = form.cleaned_data.get("email")
password = form.cleaned_data.get("password")
new_user = User.objects.create_user(username, email, password)
print(new_user)
return render(request, "accounts/register.html", context)
Agora no models.py do accounts, vamos criar a classe GuestEmail.
django_ecommerce/e_commerce/accounts/models.py
from django.db import models
class GuestEmail(models.Model):
email = models.EmailField()
active = models.BooleanField(default=True)
update = models.DateTimeField(auto_now=True)
timestamp = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.email
Vamos executar o makemigrations e o migrate, para repercutir no banco o modelo GuestEmail.
python manage.py makemigrations
python manage.py migrate
Vamos fazer agora uma mudança no forms.html do accounts.
django_ecommerce/e_commerce/accounts/templates/accounts/snippets/form.html
<form method='POST' action='{% if action_url %}{{ action_url }}{% else %}{% url "login" %}{% endif %}'> {% csrf_token %}
{% if next_url %}
<input type='hidden' name='next' value='{{ next_url }}' />
{% endif %}
{{ form }}
<button type='submit' class='btn btn-default'>Submit</button>
</form>
Agora no checkout.html do carts, faça as seguintes modificações.
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'>
<p class='lead'>Continuar como Convidado</p>
{% 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 %}
<h1>Checkout</h1>
<p>Total do carrinho: {{ object.cart.total }}</p>
<p>Frete: {{ object.shipping_total }}</p>
<p>Total: {{ object.total }}</p>
{% endif %}
{% endblock %}
Vamos importar o guest_register_view 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 .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('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)
Vamos registrar o guest profile no painel de admin.
django_ecommerce/e_commerce/accounts/admin.py
from django.contrib import admin
from .models import GuestEmail
admin.site.register(GuestEmail)
# Register your models here.
Vamos testar, faça o logout, depois entre como usuário convidado, adicione alguns produtos ao carrinho, entre no painel admin e veja que temos os emails dos usuários que logaram como convidados.
Uma coisa importante é perceber que um pedido(Order) só poderá existir depois que tivermos um billing profile, isto é, um perfil de pagamento, porque um pedido estará sempre associado a uma Order.
Então, só quando tevermos um billing profile é que associamos os produtos do carrinho a uma Order.