How do I call the email field from the default table auth_user?? needed to make users register with email, user and password

Asked

Viewed 33 times

-1

my Register.html is like this

<!DOCTYPE html>
<html lang="pt-br">
<head>

    <meta charset="UTF-8">
        <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous">

    <title>Sistema de cadastramento de Bens</title>
</head>
<body>
    <div class ='col-8 m-auto pt-2 pb-2 text-center'>
        <h1>Cidadãos cadastradoos</h1>
    </div>
    <div class="row">
    <div class ='col-8 m-auto pt-2 pb-2 text-center'>
        <a href="/accounts/login/" class="btn btn-info">Voltar</a>
    </div>

        <div class="col-8 m-auto pt-3 pb-2 text-center">
            <div class="card auth-card">
                <div class="card.body">
                    <h4 class="card-title text-center">Entrar no Sistema de Bens</h4>
<form method="post">
    {% csrf_token %}

    <div class="form-group">
        {{form.username.errors}}
        <label>Username: </label><br>
        {{form.username}}
    </div>

    <div class="form-group">
        {{form.password1.errors}}
        <label>Senha: </label><br>
        {{form.password1}}
    </div>

    <div class="form-group">
        {{form.password2.errors}}
        <label>Confirmação de senha: </label><br>
        {{form.password2}}
    </div>

    <div class="form-group">
        <input type="submit" value="Cadastrar" class="btn btn-primary">
    </div>
</form>
                </div>
            </div>
        </div>
    </div>
</body>
</html>

I tried to put the email in this pattern but it was not. Someone could help me??

my models.py

from django.db import models
from django.contrib.auth.models import User
class Cidadao(models.Model):
    nomebens = models.CharField(max_length=100)
    nomecompleto = models.CharField(max_length=150)
    numSerie = models.CharField(max_length=100)
    endereco = models.CharField(max_length=250)
    email = models.EmailField()
    observacao = models.TextField()
    user = models.ForeignKey(User, on_delete=models.CASCADE)

    def __str__(self):
        return self.user

  • show how this model class, with it can rewrite that part reuse Django authentication.

  • put on topic la,

  • you will be using the admin panel of Django to add a new user , having only a super administrator controlling it?

  • this mail in case wanted to get, because it is not related to the User class..

  • i wanted the user to register themselves so I didn’t use admin

  • 1

    Minutes, and will not have permission of groups?

  • no, you won’t have no

  • This great then, I will try to recreate this problem and explain the code

Show 3 more comments

1 answer

-1

Using Function based views.

Criação Formulario:

app user, user manager

  #app usuario
from django import forms
from django.contrib.auth.models import User # utilizando autentificacao 


class NovosuarioForm(forms.Form):
usuario = forms.CharField(required=True) #campos que seram requisitados
email = forms.EmailField(required=False)
senha = forms.CharField(required=True)


def is_valid(self): # verif se o formulario é valido

    formularioValido = True # inicia como true...

    if not super(NovosuarioForm, self).is_valid():
        print("preencha todos os campo") # caso for preenchido apenas o nome sem senha retornara invalido
        formularioValido = False

    #query que ira verificar se ja existe o usuario com mesmo nome
    novo_usuario = User.objects.filter(username=self.data['usuario']).exists()

    if novo_usuario: # apresenta uma mensagem  avisando que usuario existe
        print("usuario ja cadastrado")
        formularioValido = False # ou pode excluir, e evitando duplicata no model

    return formularioValido

How to use the User, you don’t need the model, because it will reuse the fields of the Django table.

user view

    # app usuario VIEW...
from django.shortcuts import redirect
from django.shortcuts import render
from django.contrib.auth.models import User
from django.views.generic.base import View
from perfis.models import Perfil # aplicação do usuario
from usuarios.forms import NovosuarioForm # gerenciador de usuario

#Duas aplicacões, A do usuario e um gerenciador de novos cadastros
#então um startap usuarios, que vai gerenciar
# outro startap que sera o perfil cadastrados

class RegistrarView(View):


def get(self, request): #get retorna a formulario
    return render(request, "criarLogin.html")

def post(self, request):# add dados
    form = NovosuarioForm(request.POST) # do app usuario

    if form.is_valid(): # verif se é valido
        dados_form = form.data 
        #variavel usuario puxa de User que cria usuario usando o form especificado 
        usuario = User.objects.create_user(dados_form['nome'],
                                           dados_form['email'], dados_form['senha'])
        # do model pefil, salvara o nome 
        perfil = Perfil(nome=dados_form['nome'],
                        usuario=usuario)

        perfil.save() #feito ,agora salva

        return redirect('ja_foi_adicionado.html')

    return render(request, "algumtemplate.html", {'form': form})

PROFILE MODEL:

from django.db import models
from django.contrib.auth.models import User


class Perfil(models.Model):
    nome = models.CharField(max_length=255, null=False)
    usuario = models.OneToOneField(User, related_name="perfil", on_delete='NOTHING')

The new user registration and login template are inside the app "user"

<form method="post">

    {% csrf_token %}

    <input type="text"name="nome">
    <input type="text"  name="email">  
    <input type="password" name="senha" >

   

    <button type="submit" value="Login">

</form>

USER URLS

from django.urls import path
from usuarios.views import RegistrarView
from django.contrib.auth import views

urlpatterns = [
    path('cadastrar/', RegistrarView.as_view()),
    # e os path de login e logout
]

Urlpatterns

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('perfil.urls')),
    path('', include('usuarios.urls'))
]

The Setting:

LOGIN_URL = '/login/'
LOGOUT_URL = '/logout/'
LOGIN_REDIRECT_URL = '/'


INSTALLED_APPS = [
    'perfil',
    'usuarios'
]

profile view

from perfis.models import Perfil, 
from django.contrib.auth.decorators import login_required

    @login_required
    def get_logado(request):
        return request.user.perfil

if you want another reference:

simpleisbetterthancomplex.com

  • the first and second part of the code is in view.py ??

  • The user, Registrarview is from the user, I must have confused myself, and the profile view shows if the user is logged in. a view in the user app and in the profile that indicates that it has been logged in.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.