Django上下文只传递None值

x33g5p2x  于 2023-01-31  发布在  Go
关注(0)|答案(2)|浏览(187)

我有一个视图,我想传递一个变量到我的模板,但值总是作为无传递,如数字1,2和3所示。我做错了什么请你的帮助,我知道这是一个新手问题,实际上我是非常新手。

浏览量.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)

模板.html

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

<div class="tab-pane active show" id="tabs-address-data">
     Number of ID is: {{ person }} 
</div>
mbyulnm0

mbyulnm01#

person可能是用户。只有在以下情况下才能获取此用户:
1.该request.method == 'POST'

  1. form.is_valid()返回True
    addresses相同-只有在上述两个条件为True时,才会在上下文中作为None以外的内容返回。
    在函数的开头将两者都定义为None,因此如果None值没有任何变化,它们将保持None
    GET请求的情况下,personaddresses将保持None,因为它们从未改变,这就是为什么您会看到None对应person
r6vfmomb

r6vfmomb2#

我已经修改了我的代码如下所示,谢谢你的回答.
我想知道我的算法现在是否正确。

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)

相关问题