Search
Close this search box.
Autenticação de usuários em aplicativos Django com django-allauth
Autenticação de usuários django-allauth

Posts Relacionados:

Autenticação de usuários é um requisito essencial da maioria das aplicações web. O pacote django-allauth turbina as capacidades nativas do Django nesse quesito.

Receba nossa newsletter

Autenticação de usuários com django-allauth

Autenticação de usuários é um requisito essencial da maioria dos aplicativos web. Django, o framework Python mais completo para desenvolvimento web, vem com seu sistema próprio de autenticação. Embora bom, ele falha ao não apresentar itens essenciais para a criação de aplicativos modernos. Para esses casos, a biblioteca django-allauth é a solução ideal. Neste post, mostraremos como ela pode ser facilmente utilizada para expandir as capacidades nativas do Django para autenticação de usuários. Cobriremos um passo a passo sobre como implementar registro, login, log out e mudança de senhas com django-allauth usando somente o email como requerimento e dispensando o username padrão do Django.

Pacotes necessários

Para acompanhar o post na prática, é recomendado criar um ambiente virtual. Nele, instale o Django e o pacote django-allauth:

				
					
pip install Django
pip install django-allauth

				
			

Garanta que sua versão do django-allauth é recente, pois os comandos que usaremos não funcionam em versões antigas. O código do post foi feito usando Django 5.1.6 e django-allauth 65.4.1.

início do projeto

Após as instalações, crie um novo projeto Django. O chamaremos de config:

				
					django-admin startproject config
				
			

A estrutura do projeto criado é essa:

Autenticação de usuários Django

Configuração do arquivo settings

O passo seguinte é fazer uma extensa configuração do arquivo settings.py. Localize o arquivo settings.py na pasta interna config. Nele, o primeiro passo é inserir dois novos apps na lista de apps instalados:

				
					
INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",

    "allauth", # novo
    "allauth.account", # novo

]
				
			

 Adicione o middleware necessário:

				
					MIDDLEWARE = [
    "django.middleware.security.SecurityMiddleware",
    "django.contrib.sessions.middleware.SessionMiddleware",
    "django.middleware.common.CommonMiddleware",
    "django.middleware.csrf.CsrfViewMiddleware",
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "django.contrib.messages.middleware.MessageMiddleware",
    "django.middleware.clickjacking.XFrameOptionsMiddleware",

    "allauth.account.middleware.AccountMiddleware", # novo
]

				
			

Adicione o backend de autenticação como mostrado abaixo:

				
					# novo
AUTHENTICATION_BACKENDS = [
    'django.contrib.auth.backends.ModelBackend',
    'allauth.account.auth_backends.AuthenticationBackend',
]
				
			

Também precisamos informar ao Django onde localizar os templates que usaremos. Portanto, localize no arquivo settings.py TEMPLATES “DIRS” e insira o local dos templates como mostrado abaixo:

				
					
TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [BASE_DIR / "templates"], # novo
        "APP_DIRS": True,
        "OPTIONS": {
            "context_processors": [
                "django.template.context_processors.debug",
                "django.template.context_processors.request",
                "django.contrib.auth.context_processors.auth",
                "django.contrib.messages.context_processors.messages",
            ],
        },
    },
]

				
			

Django-allauth: configurações e personalizações

Ainda no arquivo settings, agora iniciaremos as configurações que podem ser personalizadas conforme suas necessidades. O pacote django-allauth é bem rico em opções (veja aqui a lista). Faremos as mais comuns, mas você deve visitar o site oficial e conhecer outras opções disponíveis.

Primeiro, definimos uma id para o site. O default é 1 (ainda no arquivo settings.py).

				
					SITE_ID = 1

				
			

 Depois, podemos determinar se queremos enviar um email de verificação quando um usuário cria uma conta. Para esse post, deixaremos essa opção como nula.

				
					ACCOUNT_EMAIL_VERIFICATION = 'none'
				
			

Outra configuração importante é a definição da URL para qual o usuário é após entrar no app ou se registrar com sucesso. Selecionaremos a página home:

				
					LOGIN_REDIRECT_URL = '/'
				
			

Em seguida, definimos os métodos que desejamos como login. Embora ainda seja comum vermos aplicativos que usam email e username, em aplicativos modernos, o mais popular é encontrar apenas email como opção. (Também existe a opção muito popular de login social que será tema para outro post). Para usar somente o email (alterando o modo padrão de autenticação do django), adicionamos essa linha ao nosso arquivo settings.py:

				
					# cancela uso de username
ACCOUNT_LOGIN_METHODS = ["email"]  

ACCOUNT_SIGNUP_FIELDS = ['email*', 'password1*', 'password2*']

				
			

Com essas configurações, nosso arquivo settings está pronto.

Arquivo urls.py

Ainda na pasta config interna, precisamos adicionar as urls do django-allauth no arquivo urls.py:

				
					from django.contrib import admin
from django.urls import path, include # precisa adicionar include aqui

urlpatterns = [
    path("admin/", admin.site.urls),
    path("accounts/", include("allauth.urls")),  # novo - urls django-allauth
]


				
			

Django-allauth: URLS de login, sign up, logout e password reset

 Antes de continuarmos, é hora de atualizar as migrações do nosso projeto. Digite no terminal (você precisa estar dentro da pasta principal do projeto onde está o arquivo manage.py):

				
					


python manage.py migrate



				
			

Com esses passos, as páginas login, logout, register e passoword_reset já estão disponíveis para você. Elas estão disponíveis nas seguintes URLs:

login: http://127.0.0.1:8000/accounts/login/

sign-up: http://127.0.0.1:8000/accounts/signup/

logout: http://127.0.0.1:8000/accounts/logout/

Mudança de senha: http://127.0.0.1:8000/accounts/password/reset/

Para acessá-las, execute o comando no terminal para iniciar o servidor de desenvolvimento e vá até os endereços mostrados acima:

				
					


python manage.py runserver



				
			
autenticação de usuários login

Página de login padrão do django-allauth.

autenticação de usuários sign up

Página de sign up (registro) padrão do django-allauth.

autenticação de usuários password reset

Página de mudança de senha (password reset) padrão do django-allauth.

Pasta de templates e página home

Nosso de sistema de autenticação de usuários está funcionando corretamente, mas ainda não está completo. Nenhum usuário irá acessar as páginas usando diretamente os links mostrados acima quando ele entrar no nosso app. Precisamos ter uma página inicial. Portanto, criaremos uma página home onde os usuários podem ser direcionados para as páginas de registro, login, etc.

Primeiro, adicione a página home no arquivo urls.py. Para simplificar, usaremos uma class view:

				
					from django.contrib import admin
from django.urls import path, include 
from django.views.generic import TemplateView  # novo

urlpatterns = [
    path("admin/", admin.site.urls),
    path("accounts/", include("allauth.urls")),
    path("", TemplateView.as_view(template_name="home.html")), # novo
]


				
			

Depois, na pasta config externa, crie uma pasta chamada templastes e, dentro dela, um arquivo _base.html e um arquivo home.html. Com isso, a estrutura completa do nosso projeto fica assim:

django-allauth

Pasta de templates e arquivo _base.html

Em Django, assim como em outros frameworks web, é comum a presença de um arquivo HTML básico, que contém configurações e pacotes gerais usados em todas as páginas do app. As outras páginas do projeto costumam ser extensões deste arquivo. Com essa estrutura, o Django evita a repetição de diversas linhas de código que precisaríamos em cada página. Portanto, essa é a funcao do arquivo _base.html. O uso do símbolo “_” antes do nome base.html é uma convenção comum tipicamente usada para nomear arquivos parciais.

Usaremos bootstrap para adicionar configurações de estilo ao nosso site. Ele deve ser adicionado ao arquivo _base.html. No mesmo arquivo, bem no início, também faremos o load do django-allauth. Portanto, nosso arquivo _base.html completo é esse: 

				
					{% load allauth %}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link
      rel="stylesheet"
      href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css"
      integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH"
      crossorigin="anonymous"
    />
    <title>Document</title>
  </head>
  <body>
    {% block content %} {% endblock %}  <script defer src="data:text/javascript;base64,Ci8qIDwhW0NEQVRBWyAqLwp3aW5kb3cuX3dwZW1vamlTZXR0aW5ncyA9IHsiYmFzZVVybCI6Imh0dHBzOlwvXC9zLncub3JnXC9pbWFnZXNcL2NvcmVcL2Vtb2ppXC8xNS4wLjNcLzcyeDcyXC8iLCJleHQiOiIucG5nIiwic3ZnVXJsIjoiaHR0cHM6XC9cL3Mudy5vcmdcL2ltYWdlc1wvY29yZVwvZW1vamlcLzE1LjAuM1wvc3ZnXC8iLCJzdmdFeHQiOiIuc3ZnIiwic291cmNlIjp7ImNvbmNhdGVtb2ppIjoiaHR0cHM6XC9cL3d3dy5hcHJlbmRpemFydGlmaWNpYWwuY29tXC93cC1pbmNsdWRlc1wvanNcL3dwLWVtb2ppLXJlbGVhc2UubWluLmpzP3Zlcj02LjcuMiJ9fTsKLyohIFRoaXMgZmlsZSBpcyBhdXRvLWdlbmVyYXRlZCAqLwohZnVuY3Rpb24oa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BvcnRzLmV2ZXJ5dGhpbmc9bi5zdXBwb3J0cy5ldmVyeXRoaW5nJiZuLnN1cHBvcnRzW3RdLCJmbGFnIiE9PXQmJihuLnN1cHBvcnRzLmV2ZXJ5dGhpbmdFeGNlcHRGbGFnPW4uc3VwcG9ydHMuZXZlcnl0aGluZ0V4Y2VwdEZsYWcmJm4uc3VwcG9ydHNbdF0pO24uc3VwcG9ydHMuZXZlcnl0aGluZ0V4Y2VwdEZsYWc9bi5zdXBwb3J0cy5ldmVyeXRoaW5nRXhjZXB0RmxhZyYmIW4uc3VwcG9ydHMuZmxhZyxuLkRPTVJlYWR5PSExLG4ucmVhZHlDYWxsYmFjaz1mdW5jdGlvbigpe24uRE9NUmVhZHk9ITB9fSkudGhlbihmdW5jdGlvbigpe3JldHVybiBlfSkudGhlbihmdW5jdGlvbigpe3ZhciBlO24uc3VwcG9ydHMuZXZlcnl0aGluZ3x8KG4ucmVhZHlDYWxsYmFjaygpLChlPW4uc291cmNlfHx7fSkuY29uY2F0ZW1vamk/dChlLmNvbmNhdGVtb2ppKTplLndwZW1vamkmJmUudHdlbW9qaSYmKHQoZS50d2Vtb2ppKSx0KGUud3BlbW9qaSkpKX0pKX0oKHdpbmRvdyxkb2N1bWVudCksd2luZG93Ll93cGVtb2ppU2V0dGluZ3MpOwovKiBdXT4gKi8K"></script><script defer type='text/javascript' src='https://www.aprendizartificial.com/wp-content/boost-cache/static/32a3bcdfb5.min.js'></script><script
      src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.min.js"
      integrity="sha384-0pUGZvbkm6XF6gxjEnlmuGrJXVbNuzT9qBBavbLwCsOGabYfZo0T0to5eqruptLy"
      crossorigin="anonymous"
    ></script><script defer src="data:text/javascript;base64,CgkJCQljb25zdCBsYXp5bG9hZFJ1bk9ic2VydmVyID0gKCkgPT4gewoJCQkJCWNvbnN0IGxhenlsb2FkQmFja2dyb3VuZHMgPSBkb2N1bWVudC5xdWVyeVNlbGVjdG9yQ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JCQl9ICk7CgkJCQ=="></script><script data-noptimize="1">window.lazySizesConfig=window.lazySizesConfig||{};window.lazySizesConfig.loadMode=1;</script><script defer data-noptimize="1" src='https://www.aprendizartificial.com/wp-content/plugins/autoptimize/classes/external/js/lazysizes.min.js?ao_version=3.1.13'></script><script defer src="data:text/javascript;base64,d2luZG93LmFkZEV2ZW50TGlzdGVuZXIoICdsb2FkJywgZnVuY3Rpb24oKSB7CgkJCQlkb2N1bWVudC5xdWVyeVNlbGVjdG9yQWxsKCAnbGluaycgKS5mb3JFYWNoKCBmdW5jdGlvbiggZSApIHsnbm90IGFsbCcgPT09IGUubWVkaWEgJiYgZS5kYXRhc2V0Lm1lZGlhICYmICggZS5tZWRpYSA9IGUuZGF0YXNldC5tZWRpYSwgZGVsZXRlIGUuZGF0YXNldC5tZWRpYSApO30gKTsKCQkJCXZhciBlID0gZG9jdW1lbnQuZ2V0RWxlbWVudEJ5SWQoICdqZXRwYWNrLWJvb3N0LWNyaXRpY2FsLWNzcycgKTsKCQkJCWUgJiYgKCBlLm1lZGlhID0gJ25vdCBhbGwnICk7CgkJCX0gKTs="></script><script defer id="wp-postviews-cache-js-extra" src="data:text/javascript;base64,Ci8qIDwhW0NEQVRBWyAqLwp2YXIgdmlld3NDYWNoZUwxMG4gPSB7ImFkbWluX2FqYXhfdXJsIjoiaHR0cHM6XC9cL3d3dy5hcHJlbmRpemFydGlmaWNpYWwuY29tXC93cC1hZG1pblwvYWRtaW4tYWpheC5waHAiLCJub25jZSI6IjdmMGEzYTRhZTIiLCJwb3N0X2lkIjoiMjQ4NjAifTsKLyogXV0+ICovCg=="></script><script defer type='text/javascript' src='https://www.aprendizartificial.com/wp-content/boost-cache/static/9e182bc7d8.min.js'></script><script defer type="text/javascript" src="https://www.aprendizartificial.com/wp-content/cache/autoptimize/autoptimize_single_85c73559e71ad7783bef2f2d95076f32.php?ver=2.1.1807072022" id="ooohboi-steroids-js"></script><script type="text/javascript" id="jetpack-stats-js-before">_stq = window._stq || [];
_stq.push([ "view", JSON.parse("{\"v\":\"ext\",\"blog\":\"222775645\",\"post\":\"24860\",\"tz\":\"0\",\"srv\":\"www.aprendizartificial.com\",\"j\":\"1:14.4.1\"}") ]);
_stq.push([ "clickTrackerInit", "222775645", "24860" ]);</script><script type="text/javascript" src="https://stats.wp.com/e-202514.js" id="jetpack-stats-js" defer="defer" data-wp-strategy="defer"></script><script defer type='text/javascript' src='https://www.aprendizartificial.com/wp-content/boost-cache/static/a69554d1fb.min.js'></script><script defer type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.23.0/components/prism-core.min.js?ver=1.23.0" id="prismjs_core-js"></script><script defer type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.23.0/plugins/autoloader/prism-autoloader.min.js?ver=1.23.0" id="prismjs_loader-js"></script><script defer type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.23.0/plugins/normalize-whitespace/prism-normalize-whitespace.min.js?ver=1.23.0" id="prismjs_normalize-js"></script><script defer type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.23.0/plugins/line-numbers/prism-line-numbers.min.js?ver=1.23.0" id="prismjs_line_numbers-js"></script><script defer type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.23.0/plugins/toolbar/prism-toolbar.min.js?ver=1.23.0" id="prismjs_toolbar-js"></script><script defer type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.23.0/plugins/copy-to-clipboard/prism-copy-to-clipboard.min.js?ver=1.23.0" id="prismjs_copy_to_clipboard-js"></script><script defer type='text/javascript' src='https://www.aprendizartificial.com/wp-content/boost-cache/static/ef12082867.min.js'></script><script type="text/javascript" src="https://www.aprendizartificial.com/wp-includes/js/dist/i18n.min.js?ver=5e580eb46a90c2b997e6" id="wp-i18n-js"></script><script defer id="wp-i18n-js-after" src="data:text/javascript;base64,Ci8qIDwhW0NEQVRBWyAqLwp3cC5pMThuLnNldExvY2FsZURhdG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iOnsidGl0bGUiOiJTa3lwZSJ9LCJzdHVtYmxldXBvbiI6eyJ0aXRsZSI6IlN0dW1ibGVVcG9uIiwiaGFzX2NvdW50ZXIiOnRydWV9LCJtaXgiOnsidGl0bGUiOiJNaXgifSwidGVsZWdyYW0iOnsidGl0bGUiOiJUZWxlZ3JhbSJ9LCJwb2NrZXQiOnsidGl0bGUiOiJQb2NrZXQiLCJoYXNfY291bnRlciI6dHJ1ZX0sInhpbmciOnsidGl0bGUiOiJYSU5HIiwiaGFzX2NvdW50ZXIiOnRydWV9LCJ3aGF0c2FwcCI6eyJ0aXRsZSI6IldoYXRzQXBwIn0sImVtYWlsIjp7InRpdGxlIjoiRW1haWwifSwicHJpbnQiOnsidGl0bGUiOiJQcmludCJ9LCJ4LXR3aXR0ZXIiOnsidGl0bGUiOiJYIn0sInRocmVhZHMiOnsidGl0bGUiOiJUaHJlYWRzIn19LCJmYWNlYm9va19zZGsiOnsibGFuZyI6ImVuX1VTIiwiYXBwX2lkIjoiIn0sImxvdHRpZSI6eyJkZWZhdWx0QW5pbWF0aW9uVXJsIjoiaHR0cHM6XC9cL3d3dy5hcHJlbmRpemFydGlmaWNpYWwuY29tXC93cC1jb250ZW50XC9wbHVnaW5zXC9lbGVtZW50b3ItcHJvXC9tb2R1bGVzXC9sb3R0aWVcL2Fzc2V0c1wvYW5pbWF0aW9uc1wvZGVmYXVsdC5qc29uIn19OwovKiBdXT4gKi8K"></script><script defer type="text/javascript" src="https://www.aprendizartificial.com/wp-content/plugins/elementor-pro/assets/js/frontend.min.js?ver=3.23.3" id="elementor-pro-frontend-js"></script><script defer type='text/javascript' src='https://www.aprendizartificial.com/wp-content/boost-cache/static/aee954797e.min.js'></script><script defer id="elementor-frontend-js-before" src="data:text/javascript;base64,Ci8qIDwhW0NEQVRBWyAqLwp2YXIgZWxlbWVudG9yRnJvbnRlbmRDb25maWcgPSB7ImVudmlyb25tZW50TW9kZSI6eyJlZGl0IjpmYWxzZSwid3BQcmV2aWV3Ij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RpdGxlX3NyYyI6InRpdGxlIiwibGlnaHRib3hfZGVzY3JpcHRpb25fc3JjIjoiZGVzY3JpcHRpb24ifSwicG9zdCI6eyJpZCI6MjQ4NjAsInRpdGxlIjoiQXV0ZW50aWNhJUMzJUE3JUMzJUEzbyUyMGRlJTIwdXN1JUMzJUExcmlvcyUyMGVtJTIwRGphbmdvJTIwY29tJTIwZGphbmdvLWFsbGF1dGgiLCJleGNlcnB0IjoiQXV0ZW50aWNhXHUwMGU3XHUwMGUzbyBkZSB1c3VcdTAwZTFyaW9zIFx1MDBlOSB1bSByZXF1aXNpdG8gZXNzZW5jaWFsIGRhIG1haW9yaWEgZGFzIGFwbGljYVx1MDBlN1x1MDBmNWVzIHdlYi4gTyBwYWNvdGUgZGphbmdvLWFsbGF1dGggdHVyYmluYSBhcyBjYXBhY2lkYWRlcyBuYXRpdmFzIGRvIERqYW5nbyBuZXNzZSBxdWVzaXRvLiIsImZlYXR1cmVkSW1hZ2UiOiJodHRwczpcL1wvd3d3LmFwcmVuZGl6YXJ0aWZpY2lhbC5jb21cL3dwLWNvbnRlbnRcL3VwbG9hZHNcLzIwMjVcLzA0XC9kamFuZ28tYWxsYXV0aC5qcGcifX07Ci8qIF1dPiAqLwo="></script><script defer type="text/javascript" src="https://www.aprendizartificial.com/wp-content/plugins/elementor/assets/js/frontend.min.js?ver=3.23.4" id="elementor-frontend-js"></script><script defer id="elementor-frontend-js-after" src="data:text/javascript;base64,Ci8qIDwhW0NEQVRBWyAqLwoidXNlIHN0cmljdCI7IWZ1bmN0aW9uKGUsdCl7ZSh0KS5vbigiZWxlbWVudG9yL2Zyb250ZW5kL2luaXQiLChmdW5jdGlvbigpe3ZhciB0LGk9ZWxlbWVudG9yTW9kdWxlcy5mcm9udGVuZC5oYW5kbGVycy5CYXNlO3Q9aS5leHRlbmQoe29uSW5pdDpmdW5jdGlvbigpe2kucHJvdG90eXBlLm9uSW5pdC5hcHBseSh0aGlzLGFyZ3VtZW50cyksdGhpcy5pc0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pmdW5jdGlvbigpe3JldHVybiJ5ZXMiPT09dGhpcy5nZXRFbGVtZW50U2V0dGluZ3MoIl9vYl9wb3N0bWFuX3VzZSIpfSxvbkVsZW1lbnRDaGFuZ2U6ZnVuY3Rpb24oZSl7Il9vYl9wb3N0bWFuX3VzZSI9PT1lJiYoInllcyI9PT10aGlzLmdldEVsZW1lbnRTZXR0aW5ncygiX29iX3Bvc3RtYW5fdXNlIik/dGhpcy4kZWxlbWVudC5hZGRDbGFzcygib2ItcG9zdG1hbiIpOnRoaXMuJGVsZW1lbnQucmVtb3ZlQ2xhc3MoIm9iLXBvc3RtYW4iKSl9fSk7dmFyIG89eyJ0aGVtZS1wb3N0LWNvbnRlbnQuZGVmYXVsdCI6dCwidGV4dC1lZGl0b3IuZGVmYXVsdCI6dH07ZS5lYWNoKG8sKGZ1bmN0aW9uKGUsdCl7ZWxlbWVudG9yRnJvbnRlbmQuaG9va3MuYWRkQWN0aW9uKCJmcm9udGVuZC9lbGVtZW50X3JlYWR5LyIrZSwoZnVuY3Rpb24oZSl7ZWxlbWVudG9yRnJvbnRlbmQuZWxlbWVudHNIYW5kbGVyLmFkZEhhbmRsZXIodCx7JGVsZW1lbnQ6ZX0pfSkpfSkpfSkpfShqUXVlcnksd2luZG93KTsKLyogXV0+ICovCg=="></script><script defer type="text/javascript" src="https://www.aprendizartificial.com/wp-content/plugins/elementor-pro/assets/js/elements-handlers.min.js?ver=3.23.3" id="pro-elements-handlers-js"></script><script defer id="wpr-addons-js-js-extra" src="data:text/javascript;base64,Ci8qIDwhW0NEQVRBWyAqLwp2YXIgV3ByQ29uZmlnID0geyJhamF4dXJsIjoiaHR0cHM6XC9cL3d3dy5hcHJlbmRpemFydGlmaWNpYWwuY29tXC93cC1hZG1pblwvYWRtaW4tYWpheC5waHAiLCJyZXN0dXJsIjoiaHR0cHM6XC9cL3d3dy5hcHJlbmRpemFydGlmaWNpYWwuY29tXC93cC1qc29uXC93cHJhZGRvbnNcL3YxIiwibm9uY2UiOiJjMGY5NDliYWMxIiwiYWRkZWRUb0NhcnRUZXh0Ijoid2FzIGFkZGVkIHRvIGNhcnQiLCJ2aWV3Q2FydCI6IlZpZXcgQ2FydCIsImNvbXBhcmVQYWdlSUQiOiIiLCJjb21wYXJlUGFnZVVSTCI6Imh0dHBzOlwvXC93d3cuYXByZW5kaXphcnRpZmljaWFsLmNvbVwvYXV0ZW50aWNhY2FvLWRlLXVzdWFyaW9zLWVtLWFwbGljYXRpdm9zLWRqYW5nby1jb20tZGphbmdvLWFsbGF1dGhcLyIsIndpc2hsaXN0UGFnZUlEIjoiIiwid2lzaGxpc3RQYWdlVVJMIjoiaHR0cHM6XC9cL3d3dy5hcHJlbmRpemFydGlmaWNpYWwuY29tXC9hdXRlbnRpY2FjYW8tZGUtdXN1YXJpb3MtZW0tYXBsaWNhdGl2b3MtZGphbmdvLWNvbS1kamFuZ28tYWxsYXV0aFwvIiwiY2hvb3NlUXVhbnRpdHlUZXh0IjoiUGxlYXNlIHNlbGVjdCB0aGUgcmVxdWlyZWQgbnVtYmVyIG9mIGl0ZW1zLiIsInNpdGVfa2V5IjoiIiwiaXNfYWRtaW4iOiIiLCJpbnB1dF9lbXB0eSI6IlBsZWFzZSBmaWxsIG91dCB0aGlzIGZpZWxkIiwic2VsZWN0X2VtcHR5IjoiTm90aGluZyBzZWxlY3RlZCIsImZpbGVfZW1wdHkiOiJQbGVhc2UgdXBsb2FkIGEgZmlsZSIsInJlY2FwdGNoYV9lcnJvciI6IlJlY2FwdGNoYSBFcnJvciJ9OwovKiBdXT4gKi8K"></script><script defer type='text/javascript' src='https://www.aprendizartificial.com/wp-content/boost-cache/static/ba105e2afc.min.js'></script><script defer src="data:text/javascript;base64,DQogICAgICAgICAgICAgICAgKGZ1bmN0aW9uKCkgew0KICAgICAgICAgICAgICAgICAgICB2YXIgbGluayA9IGRvY3VtZW50LmNyZWF0ZUVsZW1lbnQoJ2xpbmsnKTsNCiAgICAgICAgICAgICAgICAgICAgbGluay5yZWwgPSAnc3R5bGVzaGVldCc7DQogICAgICAgICAgICAgICAgICAgIGxpbmsuaHJlZiA9ICdodHRwczovL3d3dy5hcHJlbmRpemFydGlmaWNpYWwuY29tL3dwLWNvbnRlbnQvcGx1Z2lucy9vb29oYm9pLXN0ZXJvaWRzLWZvci1lbGVtZW50b3IvYXNzZXRzL2Nzcy9zd2lwZXIubWluLmNzcyc7DQogICAgICAgICAgICAgICAgICAgIGRvY3VtZW50LmhlYWQuYXBwZW5kQ2hpbGQobGluayk7DQogICAgICAgICAgICAgICAgfSkoKTsNCiAgICAgICAgICAgIA=="></script></body>
</html>



				
			

Arquivo home.html

O arquivo home.html será bem simples. Ele estende o arquivo _base.html e possui classes bootstrap para adicionar algum estilo a seus elementos. Note que todo conteúdo desta página é mostrado dentro das tags {% block content %} e {% endblock content %}. Nosso conteúdo possui apenas uma saudação e os botões com links para registro, login e mudança de senha:

				
					{% extends "_base.html" %} {% block content %}

<div class="container">
  <div class="row justify-content-center">
    <div class="col-6">
      <h1 class="text-center mt-5">Bem-vindos ao meu site</h1>
      <div class="d-flex flex-column justify-content-around align-items-left m-1 p-1">
        <p>Selecione uma opção:</p>
        <span class="p-3"><a href="{% url 'account_signup' %}" class="btn btn-primary">Registrar</a></span>
        <span class="p-3"><a href="{% url 'account_login' %}" class="btn btn-info">Entrar</a></span>
        <span class="p-3"> <a href="{% url 'account_reset_password' %}" class="btn btn-danger">Mudar Senha</a></span>
      </div>
    </div>
  </div>
</div>

{% endblock content %}




				
			

 Note que os botões são definidos como links já contendo o endereço correto para cada URL.

Uso de condicionais no template para mostrar botão de logout

Mas onde está o botão para logout (sair)? Todo usuário que entra numa área restrita em um site precisa ter uma forma de sair. Isso geralmente é feito com o botão de logout. É claro que somente usuários logados podem sair, portanto, usaremos um condicional para mostrar o botão de logout somente para usuários autenticados. Da mesma forma, precisamos mostrar opções de login e registro apenas para usuários que não estão logados no site. Portanto, eles também devem estar dentro de nosso condicional. Para criar o condicional, usamos a variável já disponível no modelo de autenticação de usuários user.is_authenticated. Ela retorna True para usuários autenticados no app. Veja as modificações no template home.html abaixo:

				
					{% extends "_base.html" %} {% block content %}

<div class="container">
  <div class="row justify-content-center">
    <div class="col-6">
      <h1 class="text-center mt-5">Bem-vindos ao meu site</h1>
      <div class="d-flex flex-column justify-content-around align-items-left m-1 p-1">
        <p>Selecione uma opção:</p>
        {% if user.is_authenticated %}
        <span class="p-3"><a href="{% url 'account_logout' %}" class="btn btn-primary">Sair</a></span>
        {% else %}
        <span class="p-3"><a href="{% url 'account_signup' %}" class="btn btn-primary">Registrar</a></span>
        <span class="p-3"><a href="{% url 'account_login' %}" class="btn btn-info">Entrar</a></span>
        <span class="p-3"> <a href="{% url 'account_reset_password' %}" class="btn btn-danger">Mudar Senha</a></span>
        {% endif %}
      </div>
    </div>
  </div>
</div>

{% endblock content %}


				
			

Agora teste a sua aplicação registrando um usuário de teste para ver o template mudar quando ele se registra:

django-allauth

Página home para usuários não autenticados.

Ao completar seu registro, o usuário é corretamente enviado para a página home com a opção de sair (logout). Ao clicarmos nessa opção, precisamos confirmá-la para sermos reenviados de volta para a página home com as opções de registro, entrar e mudar a senha.

django-allauth

Página home para usuários autenticados.

Imagem com IA Generativa – Dia 379

IA generativa - img379

Arte com IA generativa: imagem do dia

Todos os dias postamos um exemplo de imagem artística gerada com inteligência artificial.

Tutoriais

Postagens Mais Recentes

Outras Postagens Que Podem Interessar

Veja
Mais

Fique em contato

Se inscreva para receber nossa newsletter com novidades.

aprendiz artificial