I
already got one fast and helpful answer today, so I’m going to be
greedy and press my luck.
I
have this website. Each state has their own home/landing page off the
site’s main page, and from there you will be able to get detail
pages about various tidbits about the state of your choice. I have
implemented this with a urlconf that looks for the state’s 2 digit
postal name:
url(r'^(?P<twodigit>[A-Z]{2})', include('bench.urls', namespace=twodigit)),
It
will come as no surprise that the views and templates associated with
each state are identical. However, in order to be DRY, I wanted the
view to take the twodigit argument from the url and call the right
state’s queryset. To this end, I created a dict
{'AK': 'Alaska',
'AL': 'Alabama',
'AR': 'Arkansas',
...etc…}naively
thinking I would be able to do something like
for k,v in statedict:
if twodigit == k:
state = Jurisdiction.objects.get(v)However,
this does not work. I’m not sure why. Here are some of the various
results I’ve gotten as I tried tweaking it:
for k,v in statedict:
if 'VA' == k: # I was thinking of this as almost a default value
state = Jurisdiction.objects.get(v)However,
this gets an unbound local error because of the scope, and I don’t
know how to assign the variable so that it is accessible outside the
scope of the for loop.
k='NE'
print(v)
k=="US"
print(v)
returned
U
UClearly,
there is no ‘U’ in Nebraska, so I don’t know what happened
there.
This
works
print(statedict['US'])
(aishah) malikarumi@Tetuoan2:~/Projects/aishah/jamf35$ python statedict.py
United States
But
this does not
File "statedict.py", line 63, in <module>
if statedict['k']:
KeyError: 'k'
And
this
for k, v in statedict:
if k:
print('v')Gets
me a ‘v’ for every state.
Variations
on
Jurisdiction.objects.filter(statedict[’v']) and
Jurisdiction.objects.filter(name='v’)
also
failed, and nothing
I have found on the internet has helped. Ideas?
you are looking for `statedict.items()`. (Or
`statedict.iteritems()` on py2) By default a dict just loops over
the keys. And then it unpacks your two letter string into k, v.
So the first step of your loop is k='A' and v='K'.
# urls.py
url(r'^(?P<state_code>[A-Z]{2})', views.state_home, name="state_home"),
#views.py
def state_home(request, postal_code):
state = Jurisdiction.objects.get(postal_code=postal_code)
return render(request, 'mystatetemplate.html', {'state': state})# urls.py
url(r'^(?P<postal_code>[A-Z]{2})', views.state_home, name="state_home"),