Django / Python:UnboundLocalError。我的错在哪里?

时间:2016-08-22 07:12:12

标签: python django view

models.py

class Revistapresei(models.Model):
    titlulArticol = models.CharField(max_length=300)
    textArticol = models.TextField()
    dataArticol = models.DateField(blank=True, null=True)
    linkArticol = models.CharField(blank=True, max_length=200)

    STIRIINTERNE = 'Interne'
    STIRIEXTERNE = 'Externe'
    TIP_ARTICOL_CHOICES = (
        (STIRIINTERNE, 'Interne'),
        (STIRIEXTERNE, 'Externe'),
    )
    tipArticol = models.CharField(max_length=7, choices=TIP_ARTICOL_CHOICES, default=STIRIINTERNE)

    def __str__(self):
        return self.titlulArticol

url.py

from django.conf.urls import include, url
from . import views

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^revistaPresei/$', views.revistaPresei_list, name='revistaPresei_list'),
    url(r'^revistaPresei/(?P<pk>[0-9]+)/$', views.revistaPresei_detail, name='revistaPresei_detail'),
]

views.py

from django.shortcuts import render, get_object_or_404
from .models import Revistapresei

def index(request):
    return render(request, 'blog/index.html', {})

def revistaPresei_list(request):
    revistaPreseis = Revistapresei.objects.order_by('-dataArticol')
    return render(request, 'blog/revistaPresei_list.html', {'revistaPreseis':revistaPreseis})

def revistaPresei_detail(request, pk):
    revistaPresei = get_object_or_404(revistaPresei, pk=pk)
    return render(request, 'blog/revistaPresei_detail.html', {'revistaPresei': revistaPresei})

revistaPresei_list.html

<html>
    <head>
        <title>Revista Presei List</title>
    </head>
<body>

{% for revistaPresei in revistaPreseis %}

<div>
    <p>{{ revistaPresei.dataArticol }} / {{ revistaPresei.tipArticol }}</p>
    <h1><a href="{% url 'revistaPresei_detail' pk=revistaPresei.pk %}">{{ revistaPresei.titlulArticol }}</a></h1>
    <p>{{ revistaPresei.textArticol }}</p>
</div>

{% endfor %}

</body>

revistaPresei_detail.html

<html>
    <head>
        <title>Revista Presei Detail</title>
    </head>
<body>
<div>
    {% if revistaPresei.titlulArticol %}
        <div>
            {{ revistaPresei.dataArticol }} / {{ revistaPresei.tipArticol }}
        </div>
    {% endif %}
    <h1>{{ revistaPresei.titlulArticol }}</h1>
    <p>{{ revistaPresei.textArticol }}</p>
</div>

</body>
</html>

如果我尝试选择文件中的项目 - revistaPresei_list.html - 我收到错误:

/ revistaPresei / 1 /
的UnboundLocalError 在赋值之前引用的局部变量'revistaPresei'

在代码中告诉我正确答案。

1 个答案:

答案 0 :(得分:1)

在您的函数revistaPresei_detail(request, pk)中,您在调用revistaPresei = get_object_or_404(revistaPresei, pk=pk)中有错误的参数。

get_object_or_404希望将类名作为第一个参数,因此您必须使用revistaPresei = get_object_or_404(Revistapresei, pk=pk)(检查大写和小写字母)。

目前您尝试使用局部变量revistaPresei作为参数,并且此值在通话时不存在UnboundLocalError