Home > Software engineering >  Unbound Local Error: local variable 'files' referenced before assignment
Unbound Local Error: local variable 'files' referenced before assignment

Time:01-03

Unbound Local Error: local variable 'files' referenced before assignment Getting error above: Please tell me where I am getting wrong in this code. I am beginner in Django. And I tried so many times. In this project, I am doing multiple file upload using model forms. Please help me to solve this.

views.py:

from Django. shortcuts import render
from user master. forms import Feed Model Form, File Model Form
from .models import Feed File

def create_ to_ feed(request):
    user = request. user
    if request. method == 'POST':
        form = Feed Model Form(request .POST)
        file_ form = File Model Form(request. POST, request. FILES)
        files = request. FILES. get list('file') #field name in model
        if form.is_ valid() and file_ form.is_ valid():
            feed_ instance = form. save(commit=False)
            feed_ instance. user = user
            feed_ instance. save()
            for f in files:
                file_ instance = Feed File(file=f, feed=feed_ instance)
                file_ instance. save()
    else:
        form = Feed Model Form()
        file_ form = File Model Form()
    return render(request,' user  master/multiplefile.html',{'form': form, 'file_ form': file_ form, 'files': files, 'user': user})

urls.py:
path('multiple/', views. create_ to_ feed, name='create_ to_ feed'),
] static(settings. MEDIA_ URL, document_ root= settings. MEDIA_ROOT) static(settings. STATIC_URL, document_ root=settings. STATIC_ROOT)

models.py:
from Django. d b import models

 Create your models here.
class Machine(models. Model):
    machine_ name = models. Char Field (primary_ key=True, max_ length=200)
    operation_ no = models. Integer Field()

class Feed File(models. Model):
    file = models. File Field(upload_ to = 'documents /')

class Feed(models. Model):
    machine_ name=models. Foreign Key(Machine, on_ delete=models. CASCADE, related_ name='feeds')
    text=models. Integer Field()
    files=models. Many To Many Field(Feed File)

forms.py:
from Django import forms

from Django. forms import Clearable File Input

from user master. models import Feed, Feed File
class Feed Model Form(forms. Model Form):
    class Meta:
        model = Feed
        fields = ['text']

class File Model Form(forms. Model Form):
    class Meta:
        model = Feed File
        fields = ['file']
        widgets = {
            'file': Clearable File Input(at t r s ={'multiple': True}),
        }

admin.py:
from Django. c o n t r I b import admin
from .models import Feed, Feed File, Machine
#Register your models here:
admin. site. register(Feed)
admin. site. register(Feed File)
admin. site. register(Machine)

multiplefile.html:
<!DOCTYPE html>
<html>
    <head>
        <title>Django - Multiple Files Upload</title>
    </head>
    <body>
        <div style="width: 500px; margin: auto;">
            <field set name="Multiple Files Upload">
                {% if msg %} {% auto escape off %} {{ msg }} {% end auto escape %} {% endif %}
                <form method="post" action="multiple/" e n c t y p e="multipart/form-data">
                    {% c s r f_ token %}
                    <dl>
                        <p>
                            <label>Browse and select one or more files</label>&n b s p;&n b s p;
                            <input type="file" name="files" autocomplete="off" required multiple>
                        </p>
                    </dl>
                    <p>
                        <input type="submit" value="Upload">
                    </p>
                </form>
            </field set>
        </div>
    </body>
</html>

CodePudding user response:

You have:

if request. method == 'POST':
    ...
    files = request.FILES.getlist('file') #field name in model
...
return render(request,' user  master/multiplefile.html',{'files': files})

files exists only if you send a POST request.

You can do something like this:

context = {<other context variables>}
if request.method == 'POST':
    ...
    files = request.FILES.getlist('file') #field name in model
    context['files'] = files
...
return render(request,' user  master/multiplefile.html',context)

And you should remove the spaces from your paths also.

CodePudding user response:

use this code:

    def create_ to_ feed(request):
        user = request. user
        if request. method == 'POST':
            form = Feed Model Form(request .POST)
            file_ form = File Model Form(request. POST, request. FILES)
            files = request. FILES. get list('file') #field name in model
            if form.is_ valid() and file_ form.is_ valid():
                feed_ instance = form. save(commit=False)
                feed_ instance. user = user
                feed_ instance. save()
                for f in files:
                    file_ instance = Feed File(file=f, feed=feed_ instance)
                    file_ instance.save()
            return render(request,' user  master/multiplefile.html',{'form': form, 'file_ form': file_ form, 'files': files, 'user': user})
        else:
            form = Feed.Model.Form()
            file_form = File.Model.Form()
    
        return render(request,' user  master/multiplefile.html',{'form': form, 'file_ form': file_ form, 'user': user})

Because you have defined the variable 'files' into a conditional expression, and if that conditional expression is not correct, the code will not work properly.

  • Related