alfredohb.q
alfredohb.q

Reputation: 98

log in user python, how validate a log in user?

i can't log in with a user, i am not sure why, i can log with a admin accout but, i create a model to new user and i can't log with it.

model.py

class MiUsuario(AbstractBaseUser):
    email = models.EmailField(
            verbose_name='Dirección de e-mail',
            max_length=255,
            unique=True,
        )
    nombre_completo = models.CharField(verbose_name="Nombre Completo del usuario(a)",max_length=150, unique= True, null=True)
    nombre_de_usuario = models.CharField(verbose_name="Nombre de Usuario",max_length=15, unique= True)
    Numero_de_identificacion = models.PositiveIntegerField(verbose_name="Número de identificación",null=True)
    Pagina_web = models.URLField(verbose_name="Página Web",blank=True)
    Celular = models.PositiveIntegerField(verbose_name="Número de celular",null=True)
    Telefono = models.PositiveIntegerField(verbose_name="Número de télefono",null=True)
    Ext = models.PositiveIntegerField("Extension del télefono",null=True)
    Nombre_Empresa = models.CharField(verbose_name="Nombre de la empresa",max_length=50,null=True)
    Cargo_Contacto = models.CharField(verbose_name="Cargo del cliente",max_length=50,null=True)
    GeneroEscoger = ((1,"Sin especificar"),(2,'Masculino'),(3,'Femenino'))
    Genero = models.IntegerField(verbose_name='Genero',choices=GeneroEscoger, default=1)
    Ciudades = ( (1,'Bogotá'),(2,'Medellin'),(3,'Cali'),(4,'Barranquilla'),(5,'Cartagena'),(6,'Cucuta'),(7,'Ibagué'),(8,'Bucaramanga'),(9,'Otro'))
    Ciudad = models.IntegerField(verbose_name='Ciudad',choices=Ciudades, default=1,)
    is_active = models.BooleanField(default=True)
    is_admin = models.BooleanField(default=False)

    objects = AdministracionUsuarios()

    USERNAME_FIELD = 'nombre_de_usuario'
    REQUIRED_FIELDS = ['Numero_de_identificacion','Nombre_Empresa','Telefono']

    def get_full_name(self):
        return self.nombre_completo
    def get_short_name(self):
        return self.nombre_de_usuario
    def _str_(self):
        return self.nombre_de_usuario
    def has_perm(self, perm, obj=None):
        return True
    def has_module_perms(self, app_label):
        return True
    @property
    def is_staff(self):
        return self.is_admin

then i use a form to valid if user exist in MiUsuario

form.py

class LoginUserForm(forms.Form):
    """Authentication form which uses boostrap CSS."""
    usuario = MiUsuario()
    username = forms.CharField(max_length=254,widget=forms.TextInput({'placeholder': 'Nombre de usuario'}))
    password = forms.CharField(label=_("Password"),widget=forms.PasswordInput({'placeholder':'Contraseña'}))
    def usuario():
        if  usuario.objects.filter(nombre_de_usuario!=username) and  usuario.objects.filter(password!=password):
            raise forms.ValidationError('Nombre de usuario o contraseña incorrecta')

after call the form in layout.html, but when i try log in, just relog the page and no sign with a user account, but if i try with a admin accout, relog without troubles url.py

url(r'^login$', 'app.views.index', name='Vulpini.co'),

how can i do this log Works views.py

def index(request):
    notifi = Notificaciones.objects.filter(user=request.user.id, Estado=False)
    formlog = LoginUserForm()
    if request.method == 'POST':
        form = RegistroUserForm(request.POST, request.FILES)
        if form.is_valid():
            cleaned_data = form.cleaned_data
            username = cleaned_data.get('username')
            password = cleaned_data.get('password')
            email = cleaned_data.get('email')
            user_model = MiUsuario.objects.crear_usuario(nombre_de_usuario=username,email=email, password=password)
            user_model.save()
        else:
            form = RegistroUserForm()
    else: 
        form = RegistroUserForm()
    context = {
        'formlog' : formlog,
        'form': form,
        'notifi': notifi,
    }

    return render(request,'app/index.html',context)

the view from i get the form

Upvotes: 0

Views: 82

Answers (1)

Anush Devendra
Anush Devendra

Reputation: 5475

You need to set AUTH_USER_MODEL in your settings.py with your custom user model like:

AUTH_USER_MODEL = 'appname.MiUsuario'

Changing AUTH_USER_MODEL has a big effect on your database structure. It changes the tables that are available, and it will affect the construction of foreign keys and many-to-many relationships. If you intend to set AUTH_USER_MODEL, you should set it before creating any migrations or running manage.py migrate for the first time.

Changing this setting after you have tables created is not supported by makemigrations and will result in you having to manually fix your schema, port your data from the old user table, and possibly manually reapply some migrations.

check this link for more details

Upvotes: 1

Related Questions