I try to set up a search bar, when I put a good code on the search bar, I have the product which is displayed but if it does not find the product I have an error so I put a message if it can't find the product. errore message (UnboundLocalError: local variable 'product' referenced before assignment) And the error comes at the level of the line which contains the context (context={'article':product} )
Views.py
@login_required
def search(request):
code=request.GET.get('search')
url='http://myAPI/Product/GetProduct'
x=requests.post(url)
contenu=x.json()
all_products=contenu['products']
selected_produit= next((item for item in all_products if item['code']== code),None)
if selected_produit != None:
product=selected_produit
else:
messages.error(request,'Article not found.')
context={'article':product}
return render(request,'panier/search.html',context)
search.html
{% if messages %}
{% for message in messages %}
<p {% if message.tags %} {% endif %}>{{ message }}</p>
{% endfor %}
{% endif %}
{{article.code}}
{{article.name}}
CodePudding user response:
The error explains what's wrong. If selected_product
is None
, then product
is never assigned a value. Give it a value in the else
branch, or simply use selected_product
directly since there doesn't seem to be any other use for the variable product
.