'button function doesn't work without any error - django

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

console

my website frontend

please help me to fix it. i will give my code :

views.py:

from django.shortcuts import render, redirect
from django.views.decorators.csrf import ensure_csrf_cookie
from .forms import AudioForm
from .models import Audio_store
from MusicLockApp.forms import AudioForm

@ensure_csrf_cookie
def homepage(request):
    # return HttpResponse('homepage')
    return render(request, 'homepage.html')

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 redirect("main:upload")
    form = AudioForm()
    audio = Audio_store.objects.all()
    return render(request=request, template_name="homepage.html", context={'form':form, 'audio':audio})

urls.py :

from django.contrib import admin
from django.conf.urls import url
from . import views
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.urls import path, re_path
from django.conf import settings


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

urlpatterns += staticfiles_urlpatterns()

models.py:

from django.db import models

class Audio_store(models.Model):
    record=models.FileField(upload_to='media/mp3')

forms.py:

from django import forms 
from .models import Audio_store

class AudioForm(forms.ModelForm):
    class Meta:
        model = Audio_store
        fields=['record']

add settings.py:

INSTALLED_APPS = [
    'MusicLockApp',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'crispy_forms',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

STATIC_URL = '/static/'

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'assets'),
)

MEDIA_URL = '/media/'

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

{% block content %}  

            {% load crispy_forms_tags %} 

            <div class="container">
                <div class="row">
                    <div class="col-md-6">
                        <div class="row" style="margin-top: 20px; margin-right: 10px;">
                            <button type="button" class="dsnupload">
                                <i class="large material-icons" style="font-size: 50pt; margin-top: 10px;">file_upload</i>
                                <p style="font-weight: bold; color: white;">Insert file password</p>
                            </button>
                        </div>
                        <br>
                        <div class="row" style="margin-right: 10px;">
                            <form method="POST" enctype="multipart/form-data">
                            {% csrf_token %}
                            {{form|crispy}}
                            <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>
                            <p id="message"></p>
                            </form>
                        </div>
                        <br>
                        <div class="row" style="margin-right: 10px;">
                            <div class="col-1">
                                <label class="labels" style="color: white;">Key:</label>
                                <button type="submit" class="dsnupload"></button>
                            </div>
                            <div class="col-11">
                                <input type="text" class="form-control" placeholder="insert your key here">
                            </div>
                            <br> <br>
                            <a class="dsnhide" type="button" href="#" role="button">Hide it!</a>
                        </div>
                    </div>
    
                    <div class="col-md-6">
                        <div class="row" style="margin-top: 20px;">
                            <div class="card" style="height: 13rem;">
                                <div class="card-body">
                                  <h5 class="card-title" style="text-align: center;">
                                      Progressing now
                                  </h5>
                                  <br>
                                  <div class="progress">
                                    <div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" aria-valuenow="75" aria-valuemin="0" aria-valuemax="100" style="width: 75%">75%</div>
                                  </div>
                                  <br> <br>
                                  <div class="text-center">
                                    <button id="obfuscate-button" onclick="obfuscate()">Play song</button>
                                    <a class="dsnbtn" type="button" href="#" role="button">Download</a>
                                  </div>
                                </div>
                            </div>
                        </div>
                        <br>
                        <div class="row">
                            <div class="card">
                                <div class="card-body">
                                  <h5 class="card-title">Information Music</h5>
                                  <p class="card-text">Song :</p>
                                  <p class="card-text">Artist :</p>
                                  <p class="card-text">Album :</p>
                                  <p class="card-text">Year :</p>
                                  <p class="card-text">Genre :</p>
                                  <p class="card-text">Duration :</p>
                                </div>
                              </div>
                        </div>
                    </div>
                </div>
            </div>

            {% endblock %}

what i want is = when i click button insert audio file, we can choose file from local and when clicked button hide it, it will upload it to local folder.

error error1



Solution 1:[1]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1