Home > Enterprise >  button function doesn't work without any error - django
button function doesn't work without any error - django

Time:05-14

So i want to make models form to upload file mp3. I was copy the code from website, but suddenly it's not work. there's no error message in terminal or console too.

when i clicked button audiotrack, what my terminal shown just

[12/May/2022 22:11:00] "POST / HTTP/1.1" 200 8928

error error1

CodePudding user response:

That's because you have two different views rendered into your same homepage template. The POST method will never be sent to your DB. You have two options:

1. If you want different views, add it to urlpatterns, in your form put action="{% url 'upload_url' %}"

views.py

@ensure_csrf_cookie
def homepage(request):
    form = AudioForm()
    audio = Audio_store.objects.all()
    context = {'form': form, 'audio': audio}

    return render(request, 'homepage.html', context=context)

def decode(request):
    # return HttpResponse('about')
    return render(request, 'decode.html')

def upload(request):
    if request.method == "POST":
        form = AudioForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
        return HttpResponseRedirect(request.META.get('HTTP_REFERER'))  # redirect previous page
    return redirect("main:homepage")

urls.py

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^decode/$', views.decode),
    url(r'^$', views.homepage),
    url(r'^upload/$', views.upload), # here
    path('audio', views.Audio_store),
]

html

<form method="POST" action="{% url 'main:upload' %}" enctype="multipart/form-data">

2. The simplest way is to render the form in the same page as the POST request.

views.py

def homepage(request):
    form = AudioForm()
    audio = Audio_store.objects.all()
    if request.method == "POST":
        form = AudioForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
        return redirect("main:homepage")

    context={'form':form, 'audio':audio}
    return render(request, "homepage.html", context=context)

def decode(request):
    # return HttpResponse('about')
    return render(request, 'decode.html')

This way, you don't need to add another urlpattern and modify your form action.

  • Related