pythondjangodjango-1.10

UnboundLocalError-local variable 'app' referenced before assignment


bu benim appname.urls kodlarım [appname: atolye (bu bir Türk kelimesi)]

from django.conf.urls import url from .views import * urlpatterns = [

url(r'^index/$', atolye_index),
url(r'^(?P<id>\d+)/$', atolye_detail), 

] ve bu benim atolye.views

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

def atolye_index(request): atolyes=atolye.objects.all() return render(request, 'atolye_index.html', {'atolyes':atolyes})

def atolye_detail(request, id): atolye = get_object_or_404(atolye, id=id) context = { 'atolye': atolye, } return render(request, 'atolye_detail.html', context) Bu kodu kullanmak istiyorum ama işe yaramıyor. Ne yapmalıyım?

python: 3.5.3 django: 1.10 win7 Yeni bir kullanıcıyım. Kötü ingilizcem için özür dilerim.


Solution

  • I'm taking a bit of a guess here, because your exception traceback doesn't match either your title or your description, and your code is unreadable, but…

    from .models import atolye
    
    # …
    
    def atolye_detail(request, id):
        atolye = get_object_or_404(atolye, id=id) 
    

    This last line is probably the one with the exception, and the unbound local is probably not app or the other one you mentioned but atolye, right?

    The problem is that if you assign to a name anywhere in a function, that name is always a local variable in that function.

    So, since you have atolye = here, atolye is a local variable. Even in get_object_or_404(atolye, id=id). And, since that call happens before you've assigned anything to atolye, the local variable has no value.


    I'm not sure what you're trying to do here, but there are two possibilities.

    If you weren't trying to replace the global value of atolye, just use a different name:

    def atolye_detail(request, id):
        my_atolye = get_object_or_404(atolye, id=id) 
        context = { 'atolye': my_atolye, }
        return render(request, 'atolye_detail.html', context)
    

    If you were trying to replace the global value of atolye, you need a globalstatemen:

    def atolye_detail(request, id):
        global atolye
        atolye = get_object_or_404(atolye, id=id) 
        context = { 'atolye': atolye, }
        return render(request, 'atolye_detail.html', context)