Django local variable 'vaiable' referenced before assignment

0

Good morning. I could not solve this error "local variable" - 'referenced before assignment ", my code is this:

Vista:

 def palcosSearch(request):
 if request.method == 'POST':
     form = SearchPalco(request.POST)

     if form.is_valid(): 
         NamePalco = form.cleaned_data('palco')
         palcos = Palco.objects.filter(palcoName=NamePalco)        
 else:
    form=SearchPalco()
    palcos=None
 return render(request,'ExamenTemplates/palcosSearch.html',{"form": 
 form,"palcos":palcos})

Model

class Palco(models.Model):
Category = models.CharField(max_length = 255)
palcoName = models.CharField(max_length = 255)
capacity = models.IntegerField()
location =  models.CharField(max_length = 255)
class Meta:
    db_table = "Palco"

def __str__(self):
    return self.palcoName

Form

class SearchPalco(forms.Form):
palco = forms.ModelChoiceField(label='Palco',initial='',
                            widget=forms.Select(),
                             queryset=None)

def __init__(self,*args,**kwargs):
    super(SearchPalco,self).__init__(*args,**kwargs)
    self.fields['palco'].widget.attrs['class']= 'form-control'
    self.fields['palco'].widget.attrs['placeholder']= 'Ingrese palco.'
    self.fields['palco'].queryset = 
    Palco.objects.values_list('palcoName', flat=True)

I know the reason is that the condition does not pass in is_valid() view but I can not find why.

    
asked by lbarajas 08.10.2018 в 04:02
source

1 answer

0

The code that you sample is badly indented (surely an error when doing the cut / paste) so it is not very reliable to venture conclusions about it.

Suppose that the correct indentation is as follows (which is a reasonable assumption):

 def palcosSearch(request):
    if request.method == 'POST':
        form = SearchPalco(request.POST)

        if form.is_valid(): 
            NamePalco = form.cleaned_data('palco')
            palcos = Palco.objects.filter(palcoName=NamePalco)        
    else:
        form=SearchPalco()
        palcos=None
    return render(request,'ExamenTemplates/palcosSearch.html',{"form": 
    form,"palcos":palcos})

Then look. If the method is POST, the first if is fulfilled. But if after form.is_valid() were False , that if nested is not executed, and then the variable palcos is not assigned. The else: belongs to the if more exterior, so it is not executed either. We therefore arrive at the return without assigning anything to the variable palcos , but the return reference that variable.

Therefore you have the indicated error: referenced variable before it has been assigned.

You can solve this in two ways. Either give the variable a default value before the if , or you give it a else of the if internal%.

In any case this has nothing to do with the latest version of python or Django, it is usual when you try to use a variable that has no value yet.

    
answered by 09.10.2018 в 08:41