Home > Net >  Django context pass only None value
Django context pass only None value

Time:01-31

I have a view where I want to pass a variable to my template, however the value is always passed as None, as shown in numerals 1 , 2 and 3. What am I doing wrong please your help, I know it's a newbie question, actually I'm very newbie.

views.py

def create_address(request, dni):
    person = None
    addresses = None
        
    if request.method == 'POST':
        form = CreateAddressForm(request.POST)
        if form.is_valid():
            try:            
                person = Persona.objects.get(numero_documento=dni)
                addresses = Direccion.objects.filter(numero_documento=dni)
                print(f'Persona: {person}') # this print person ID.
            
                f = form.save(commit=False)
                f.numero_documento = person
                f.save()
                
                messages.success(request,
                    'Dirección registrada con éxito.'
                )
                if 'save' in request.POST:
                    return HttpResponseRedirect(reverse('persons:list'))
                if 'add_data' in request.POST:
                    return HttpResponseRedirect(reverse('persons:create_address', kwargs={'dni': dni}))            
            except Persona.DoesNotExist:
                messages.error(
                    request,
                    'El número de DNI no existe en la base de datos.'
                )
            except Direccion.DoesNotExist:
                addresses = None
                messages.error(
                    request,
                    'No se ha registrado ninguna dirección.'
                )                        
        else:
            messages.error(
                request,
                'No se pudo registrar la dirección.'
            )
    else:
        form = CreateAddressForm()
    template = 'persons/addresses/create_address.html'
    context = {
        'pre_title': 'Direcciones domiciliarias',                   
        'person': person, # (2) The value of "person" is "None".
        'form': form,            
        'addresses': addresses,
    }    
    return render(request, template, context)

template.html

(3) Value of "person" is "None".  

<div  id="tabs-address-data">
     Number of ID is: {{ person }} 
</div>

CodePudding user response:

A person is probably a user. You only get this user if:

  1. the request.method == 'POST'
  2. the form.is_valid() returns True

Same with addresses - this only gets returned in the context as something other than None if the above two conditions are True.

You define both at the beginning of the function as None, so if nothing changes the None values, they will stay None.

In the case of a GET request, person and addresses will stay None because they never change. This is why you are seeing None for person.

CodePudding user response:

I have modified my code as shown below, thanks for your answers.

I would like to know if my algorithm is now correct.

def create_address(request, dni):
    try:
        person = Persona.objects.get(numero_documento=dni)
        addresses = Direccion.objects.filter(numero_documento=dni)
    except Persona.DoesNotExist:
        person = None
        messages.error(
            request,
            'El número de DNI no existe en la base de datos.'
        )
    except Direccion.DoesNotExist:
        addresses = None
        messages.error(
            request,
            'No se ha registrado ninguna dirección.'
        )

    if request.method == 'POST':
        form = CreateAddressForm(request.POST)
        
        if form.is_valid():
            f = form.save(commit=False)
            f.numero_documento = person
            f.save()

            messages.success(
                request,
                'Dirección registrada con éxito.'
            )
            
            if 'save' in request.POST:
                return HttpResponseRedirect(reverse('persons:list_persons'))
            if 'add_data' in request.POST:
                return HttpResponseRedirect(reverse('persons:create_address', kwargs={'dni': dni}))

        else:            
            messages.error(
                request,
                'No se pudo registrar la dirección.'
            )
    else:    
        form = CreateAddressForm()
        
    template = 'persons/addresses/create_address.html'
    context = {
        'pre_title': 'Direcciones domiciliarias',
        'title': f'{person.nombres} {person.apellido_paterno} {person.apellido_materno}',

        'object': person,
        'form': form,

        'addresses': addresses,
    }
    return render(request, template, context)
  • Related