what mean the error local variable 'instance' referenced before assignment

i am trying to get values from the views.py function into the html template but the system crash and display this error :

local variable 'instance' referenced before assignment

views.py

def update(request,pk):
    #deny anonymouse user to enter the  detail page
    if not request.user.is_authenticated:
            return redirect("login")
    else:
        if request.method == "POST":
            instance = get_object_or_404(suspect,pk=pk)
            print(suspect)
        context = {
        "title":instance.suspect_name,
        "instance":instance,
      }
        return render(request,'blog/update.html',context)

update.html

{{instance.id}}

its just a test because what i want is to be able to update form based on the id so i am trying to get the id of the object.

i will appreciate any help

3 answers

  • answered 2019-07-21 18:50 Astik Anand

    If the if conditions fails then instance variable will not be available and hence it's giving error local variable 'instance' referenced before assignment.

    To avoid that, you can define the context dict first and then update value inside.

    views.py

    def update(request,pk):
        context = {}
        #deny anonymouse user to enter the  detail page
        if not request.user.is_authenticated:
                return redirect("login")
        else:
            if request.method == "POST":
                instance = get_object_or_404(suspect,pk=pk)
                print(suspect)
                context.update ({"title":instance.suspect_name, "instance":instance})
    
            return render(request,'blog/update.html',context)
    

    HTML

    Check if instance is present and then show.

    {% if instance %}
        {{instance.id}}
    {% endif %}
    

  • answered 2019-07-21 18:53 Alex

    it means you try to use instance, but it is unknown because it never get past one of the if statements, possibly because user was not logged in or because requestmethod is not POST.

    This would fix it:

    def update(request,pk):
        #deny anonymouse user to enter the  detail page
        if not request.user.is_authenticated:
                return redirect("login")
    
        if request.method == "POST":
            instance = get_object_or_404(suspect,pk=pk)
            print(suspect)
            context = {
               "title":instance.suspect_name,
               "instance":instance,
             } 
        else:
            context = {}
        return render(request,'blog/update.html',context)
    

    (I removed your else statement, becuase it does not make much sense there )

  • answered 2019-07-21 19:07 ahmad

    Its because request.method may not be "POST", so add condition to your code:

    update.html

    {% if instance %} 
    {{instance.id}}
    {% endif %}