Zeed Tanue
Zeed Tanue

Reputation: 121

reason behind "local variable 'variable ' referenced before assignmen" ERROR

I am not much familiar with django. Was working on a learning project. So here I am getting the error which says UnboundLocalError, "local variable 'url_array' referenced before assignment" . Here's my form.py , views.py and html code. Please have a look and give me a solution.

forms.py

from django import forms
from .models import Images

class ImageForm(forms.ModelForm):
    class Meta:
        model = Images
        fields = ('__all__')

views.py

class Upload(View):

    def post(self, request):

        form = ImageForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            imageZip=request.FILES
            fs = FileSystemStorage()
            url_array = []


            with ZipFile(imageZip['image'], 'r') as zip:
                zip.extractall()
                unzip_file= zip.namelist()
                for files in unzip_file:
                    with open(files, "rb") as file:
                        name = fs.save('read.jpg', file)
                    url_array.append(fs.url(name))
        else:
            form = ImageForm()


        return render(request, 'toDo_app.html', context = {'form': form, 'url':url_array})

toDo_app.html

<form  class="" enctype="multipart/form-data" action="/upload/" method="post">
          {% csrf_token %}
          {{ form.as_p }}
          <button type="submit" >Upload</button>


       </form>

          <br>

          {% if url %}
            <p>Uploaded file: </p>
            <ul>
              {% for urls in url %}
                <li>  <a href="{{ urls }}">{{ urls }}</a> </li>
                {% endfor %}

            </ul>



          {% endif %}

So my error is at return render(request, 'toDo_app.html', context = {'form': form, 'url':url_array}) line. Thanks for your time and I would be really grateful for an explanation and solution

Upvotes: 0

Views: 114

Answers (2)

Rafael
Rafael

Reputation: 7242

The variable url_array is initialised within the one body of the if statement. There is a chance that the if statement is never evaluated as True and hence the url_array will be uninitialised by the time your function returns. The function will not be able to return render(...) because url_array has no value.

Just make sure that the url_array is initialised with some default value outside the if statement, in the same scope with the return statement.

Upvotes: 1

Manickam deva
Manickam deva

Reputation: 27

assign a url_array before if block

def post(self, request):
           url_array = []
           form = ImageForm(request.POST, request.FILES)

Upvotes: 1

Related Questions