DJANGO FORM - how to change save location file uploaded

368 Views Asked by At

i don't use models form but only form. How to change location file when i uploaded? i want the file just go to /mp3 folder. And now it not move to anything (the file didn't got upload).

and this my code :

def homepage(request):
if request.method == "POST":
    form = Audio_store(request.POST, request.FILES)
    #  form = AudioForm(request.POST, request.FILES)
    if form.is_valid():
         handle_uploaded_file(request.FILES['record'])
    return render(request, "homepage.html", {'form': form})
else:
      return render(request, "homepage.html")


def handle_uploaded_file(f):
    with open('mp3', 'wb+') as destination:
        for chunk in f.chunks():
            destination.write(chunk)

forms.py :

 from django import forms
    
    class Audio_store(forms.Form):
        record=forms.FileField()

urls.py:

urlpatterns = [
     url(r'^admin/', admin.site.urls),
     url(r'^decode/$', views.decode),
     path("", views.homepage, name="upload")
 ]

if settings.DEBUG: #add this
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

html :

<form method="POST" enctype="multipart/form-data">
                            {% csrf_token %}
                            {{form}}
                            <button type="submit" class="dsnupload">
                                <i class="large material-icons" style="font-size: 50pt; margin-top: 10px;">audiotrack</i>
                                <p style="font-weight: bold; color: white;">Insert file audio (mp3)</p>
                            </button>
                          </form>

and my error msg : cannot upload

my folder: folder

1

There are 1 best solutions below

5
On

Hey As I saw your code and find that it is giving the reference before assignment error as of my experience in django it comes when it can't find the variable which we specify like form in your case and your code is not working because:-

  1. You are only handling the post request and then returning render method with some context

  2. Error is coming bcoz you are making GET request as you can see the request method as GET and it is also returning the render method but with some context which is form and django can't find the form so it is giving the error just handle GET request as well below is the code which is in my mind to solve the error:

code:

def homepage(request):
    if request.method == "POST":
        form = Audio_store(request.POST, request.FILES)
        #  form = AudioForm(request.POST, request.FILES)
        if form.is_valid():
             handle_uploaded_file(request.FILES['record'])
             return HttpResponseRedirect('mp3/')
        return render(request, "homepage.html", {'form': form})
     else:
          return render(request, "homepage.html")