Local variable 'client' referenced before assignment

1

I want to protect the view of a template, since I have several types of extended users with model User of Django, I find it difficult to work. I have already tried it in many ways but without success, this is one and it gives me error.

This is the view:

def ViajesCliente(request, id_cliente):
    if request.user.is_authenticated:
        usuario = request.user.id

        try:
            cliente = Cliente.objects.get(usuario_id = usuario)
            bandera = True
        except cliente.DoesNotExist:
            bandera = False

        if bandera == True:
            if cliente.id == id_cliente:
                viajes = Viaje.objects.filter(cliente_id = id_cliente)
                viajes_p = Viaje.objects.filter(cliente_id = id_cliente, estado = 'P')
                viajes_c = Viaje.objects.filter(cliente_id = id_cliente, estado = 'C')
                viajes_r = Viaje.objects.filter(cliente_id = id_cliente, estado = 'R')
                contexto = {
                'viajes': viajes,
                'viajes_p': viajes_p,
                'viajes_c': viajes_c,
                'viajes_r': viajes_r,
                }
                return render(request, 'cliente/servicio.html', contexto)
    return HttpResponseRedirect(reverse('home:index'))

These are the models:

from django.db import models
from django.contrib.auth.models import User
from datetime import date, datetime
# Create your models here.


class Cliente(models.Model):
 usuario = models.OneToOneField(User, on_delete = models.CASCADE)
 cedula = models.CharField(max_length = 10, unique = True)
 telefono = models.CharField(max_length = 12)
 rol = models.CharField(max_length = 20)

class BitacoraCliente(models.Model):
 user = models.ForeignKey(Cliente, on_delete = 'cascade', default = None)
 descripcion = models.CharField(max_length = 20)
 fecha = models.DateField(default = datetime.today)
    
asked by Jonnathan Carrasco 16.03.2018 в 02:41
source

2 answers

1

As @eyllanesc mentions, the problem is that DoesNotExist is an exception to the model, so the correct thing would be:

try:
    cliente = Cliente.objects.get(usuario_id = usuario)
    bandera = True
except Cliente.DoesNotExist:
    bandera = False

Since cliente is the variable you are trying to assign, hence the error.

Another way to do this is to use ObjectDoesNotExist which is the base class to capture exceptions when the object does not exist in the database:

from django.core.exceptions import ObjectDoesNotExist

# ...

try:
    cliente = Cliente.objects.get(usuario_id = usuario)
    bandera = True
except ObjectDoesNotExist:
    bandera = False

This exception will capture the error for any model .

    
answered by 16.03.2018 в 15:22
0

There are some comments that I will put to you as a comment

def ViajesCliente(request, id_cliente):
    if request.user.is_authenticated:
        usuario = request.user # aqui es mejor coger el objecto completo django se encarga de la comparacion 

        try:
            # he quitado el "_id" para igualar directamente con el objeto, 
            # pero si quisieras igualarlo con el id de igual manera lo correcto 
            # seria poner dos guiones bajos asi : "usuario__id=usuario.id" para 
            # acceder a un atributo (id o nombre, etc) de un atributo objeto (usuario) 
            # desde un objeto modelo (Cliente) se usa el doble guion bajo
            cliente = Cliente.objects.get(usuario = usuario) 
            # esto lo pongo aqui para quitarnos un if y una variable
            if cliente.id == id_cliente:
                viajes = Viaje.objects.filter(cliente_id = id_cliente)
                viajes_p = Viaje.objects.filter(cliente_id = id_cliente, estado = 'P')
                viajes_c = Viaje.objects.filter(cliente_id = id_cliente, estado = 'C')
                viajes_r = Viaje.objects.filter(cliente_id = id_cliente, estado = 'R')
                contexto = {
                'viajes': viajes,
                'viajes_p': viajes_p,
                'viajes_c': viajes_c,
                'viajes_r': viajes_r,
                }
                return render(request, 'cliente/servicio.html', contexto)
        except Cliente.DoesNotExist: # la excepcion la tienes que hacer apartir del modelo y no de tu variable
            pass         
    return HttpResponseRedirect(reverse('home:index'))
    
answered by 18.03.2018 в 00:56