I have a problem with Django.
My error message:
UnboundLocalError at /city/city
local variable ‘adv_city’ referenced before assignment
Traceback: http://dpaste.com/751727/
views:
def advert_by_city(request):
c = request.GET.get('city', '')
if c:
adv_city = Advert.objects.filter(city=c)
adverts = Advert.objects.values('city').distinct()
return render_to_response('advert_by_city', {'adverts':adverts},{'adv_city':adv_city}, context_instance=RequestContext(request))
template:
{% for city in adverts %}
<a href="city?{{ city.city }}"/>{{city.city}}</a>
<br/>
{% endfor %}
{% for adverts in adv_city%}
{{adverts.title}}
{% endfor%}
model:
class Advert(models.Model):
title = models.CharField(max_length=255)
city = models.CharField(max_length=255)
How to fix it?
You should give a default value for
adv_cityin casecevaluates to false. For instance, an empty list might work in your case:If you don’t do that, and
cis false (Python treats the empty string as false, as you may know), then theadv_cityvariable will not be considered assigned.If you can have a valid
Advertwith an empty string as thecityattribute, then just remove theifand let the filter run for any value ofc.