English 中文(简体)
Django Get 方法。 任务前引用的本地变量
原标题:Django GET method. Local variable referenced before assignment
  • 时间:2012-05-24 05:42:30
  •  标签:
  • django

我对决哥有意见

我的错误消息 :

UnboundLocalError at /city/city local variable adv_city referenced before assignment

追踪:http://dpaste.com/757/

观点:

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))

模板 :

{% for city in adverts %}
    <a href="city?{{ city.city }}"/>{{city.city}}</a>
<br/>
{% endfor %}

{% for adverts in adv_city%}
    {{adverts.title}}
{% endfor%}

模型 :

class Advert(models.Model):

    title = models.CharField(max_length=255)
    city = models.CharField(max_length=255)

如何修补?

最佳回答

adv_city 评估为假的情况下,您应该给 adv_city 给出一个默认值。 例如,空列表在您的情况下可能有效 :

c = request.GET.get( city ,   )
adv_city = Advert.objects.filter(city=c) if c else []

如果您不这样做, 且 c 是假的 ( Python 将空字符串视为假的, 您可能知道), 那么 < code>adv_ city 变量将不会被视作指定 。

如果您有有效的 Advert , 以空字符串作为 city 属性, 那么只需删除 if , 让过滤器运行为 c 的任何值 。

问题回答

您应该登录 c 的值, 我认为您的代码在 if 内没有达到代码, 如果您在 request. GET.get (城市,) 中给它一个默认值, 则空字符串不会在 if 中出现。





相关问题
How to get two random records with Django

How do I get two distinct random records using Django? I ve seen questions about how to get one but I need to get two random records and they must differ.

Moving (very old) Zope/Plone Site to Django

I am ask to move data from a (now offline) site driven by Plone to a new Django site. These are the version informations I have: Zope Version (unreleased version, python 2.1.3 ) Python Version 2.1....

Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

Flexible pagination in Django

I d like to implement pagination such that I can allow the user to choose the number of records per page such as 10, 25, 50 etc. How should I go about this? Is there an app I can add onto my project ...

is it convenient to urlencode all next parameters? - django

While writing code, it is pretty common to request a page with an appended "next" query string argument. For instance, in the following template code next points back to the page the user is on: &...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

热门标签