按钮功能无法正常工作 - django

button function doesn't work without any error - django

所以我想制作模型来上传文件mp3。我是从网站上复制代码,但突然不行了。终端或控制台也没有错误消息。

当我点击音轨按钮时,我的终端显示的是

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

console

my website frontend

请帮我解决一下。我会给出我的代码:

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']

添加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 %}

我想要的是=当我点击按钮插入音频文件时,我们可以从本地选择文件,当点击按钮隐藏它时,它会上传到本地文件夹。

那是因为您在同一个 homepage 模板中呈现了两个不同的视图。 POST 方法永远不会发送到您的数据库。您有两个选择:

1。如果您想要不同的视图,请将其添加到 urlpatterns,在您的表单中输入 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。最简单的方法是在与 POST 请求相同的页面中呈现表单。

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')

这样,您就不需要添加另一个 urlpattern 和修改您的表单 action