views.py
def paitent(request):
search_query = ''
if request.GET.get('search_query'):
search_query = request.GET.get('search_query')
if search_query == ' ':
print('Ex')
else:
userprofile = Profile.objects.filter(id=search_query)
profiles = Totallcount.objects.filter(image_owner=search_query)
context = {
'profiles':profiles,
'userprofile':userprofile,
}
return render(request, "medical_report/paitent.html",context)
paitent.html
<form id='searchForm' action="{% url 'paitent' %}" method="get">
<div >
<input
type="search"
placeholder="Search by Name"
aria-label="Search"
id="formInput#search" type="text" name="search_query" value="" />
<button type="submit" value="Search">
<i ></i>
</button>
</div>
</form>
Error.
UnboundLocalError at /paitent/
local variable 'profiles' referenced before assignment
Request Method: GET
Request URL: http://127.0.0.1:8000/paitent/?search_query=
Django Version: 3.2.15
Exception Type: UnboundLocalError
Exception Value:
local variable 'profiles' referenced before assignment
Exception Location: C:\Users\21100002\Desktop\myreports\medical_report\views.py, line 176, in paitent
Python Executable: C:\Users\21100002\Desktop\ocr\env\Scripts\python.exe
Python Version: 3.7.0
CodePudding user response:
Consider what happens if:
if request.GET.get('search_query')
...returns a falsy value.
In such a case neither userprofile nor profiles will exist yet you try to use then unconditionally in you context dictionary construction
CodePudding user response:
Look at this section:
if request.GET.get('search_query'):
search_query = request.GET.get('search_query')
if search_query == ' ':
print('Ex')
else:
userprofile = Profile.objects.filter(id=search_query)
profiles = Totallcount.objects.filter(image_owner=search_query)
context = {
'profiles':profiles,
'userprofile':userprofile,
}
return render(request, "medical_report/paitent.html",context)
If search_query
is equal to whitespace " "
, then it prints ('Ex'
) and move to context, where it needs profiles
, but it didn't set that variable. You need to create proper values in if search_query == ' '
and add else
for if request.GET.get('search_query')
condition, in example like this:
if request.GET.get('search_query'):
search_query = request.GET.get('search_query')
if search_query == ' ':
print('Ex')
userprofile = Profile.objects.all()
profiles = Totallcount.objects.all()
else:
userprofile = Profile.objects.filter(id=search_query)
profiles = Totallcount.objects.filter(image_owner=search_query)
else:
userprofile = Profile.objects.all()
profiles = Totallcount.objects.all()
context = {
'profiles': profiles,
'userprofile': userprofile,
}
return render(request, "medical_report/paitent.html",context)
Every variable you use has to be firstfully set in every possible way in your algorithm.