禁止(CSRF令牌缺失或不正确。): /音频
我有带有按钮的网站可以在帖子上上传音频mp3。问题是,当我单击按钮时,它是新的/(http:// localhost:8000/audio)实际上只是http:// localhost:8000。当我看到terimal时,有错误消息
禁止(CSRF令牌缺失或不正确。): /audio < /p>
同时,我的网站上有错误消息
禁止(403)CSRF验证失败。请求中止。
有助于失败的原因:
CSRF令牌缺失或不正确。 通常,当有真正的跨站点请求伪造或尚未使用Django机构时,可能会发生这种情况 正确。对于发布表格,您需要确保:
您的浏览器正在接受cookie。视图功能通过请求 到模板的渲染方法。在模板中,有一个{% CSRF_TOKEN%}在每个帖子表单中的模板标签 内部URL。如果您不使用csrfviewmiddleware,则必须 在使用CSRF_Token模板标签的任何视图上使用CSRF_PROTECT,作为 以及那些接受帖子数据的人。该表格具有有效的CSRF 令牌。登录另一个浏览器选项卡或击中背面后 登录后的按钮,您可能需要用表单重新加载页面, 因为在登录后旋转令牌。您正在看到帮助 此页面的部分是因为您在django中有debug = true 设置文件。将其更改为false,只有初始错误 消息将显示。
您可以使用CSRF_FAILURE_VIEW设置自定义此页面。
我想要的是,我可以在没有数据库的情况下将文件mp3上传到Django(只是本地)。歌曲可以由艺术家,持续时间
信息
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
from django.conf.urls.static import static
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^decode/$', views.decode),
url(r'^$', views.homepage),
path('audio', views.Audio_store),
]
urlpatterns += staticfiles_urlpatterns()
,
from django.http import HttpResponse
from django.shortcuts import render
from django.views.decorators.csrf import ensure_csrf_cookie
from subprocess import call
from django.core.files import File
from django.views.decorators.csrf import csrf_exempt
import subprocess
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')
#@csrf_exempt
def obfuscate(request):
print("HI")
if request.method == 'GET':
return HttpResponse("Hi")
if request.method == 'POST':
print("files: " + str(request.FILES))
print("posts: " + str(request.POST))
if len(request.POST) > 0:
handle_uploaded_file(request.FILES['audio_file'])
return HttpResponse("The form was valid!")
def handle_uploaded_file(f):
with open('temp.mp3', 'wb+') as destination:
for chunk in f.chunks():
destination.write(chunk)
subprocess.check_call("ffmpeg -y -i temp.mp3 temp.wav", shell=True)
def Audio_store(request):
if request.method == 'POST':
form = AudioForm(request.POST, request.FILES or None)
if form.is_valid():
form.save()
return HttpResponse('SUKSES BRUH')
else:
form = AudioForm()
return render(request, 'homepage.html', {'form' : form})
来
from django import forms
from django.db import models
class Audio_store(models.Model):
record=models.FileField(upload_to='media/mp3')
class Meta:
db_table='Audio_store'
定义
from django import forms
from MusicLockApp.models import *
class AudioForm(forms.ModelForm):
class Meta:
model=Audio_store
fields=['record']
流派
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 = '/mp3/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'mp3')
等
<script>
var file = undefined;
var audio_formats = ["mp3"];
// using jQuery
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
function fileAdded() {
var x = document.getElementById("audio-file");
file = x.files[0];
var msg = document.getElementById("message");
if (file != undefined) {
x = file.name.split(".");
var ext = x[x.length - 1];
if (audio_formats.indexOf(ext) == -1) {
msg.innerHTML = ext + " is not an audio file!";
} else {
msg.innerHTML = file.name + " has been successfully added!";
}
} else {
msg.innerHTML = "Please select an audio file to obfuscate!";
}
}
function obfuscate() {
if (file == undefined)
alert("Choose an audio file!");
else {
var obfuscateButton = document.getElementById("obfuscate-button");
obfuscateButton.innerHTML = "Proccessing...";
var xhr = new XMLHttpRequest();
var url = "http://127.0.0.1:8000/obfuscator/obfuscate/";
var method = 'POST';
xhr.onreadystatechange = function() {
if(xhr.readyState === 4 && xhr.status === 200) {
obfuscateButton.innerHTML = "Done!"
}
}
xhr.open(method, url, true);
xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
var formData = new FormData();
formData.append("audio_file", file);
formData.append("file_name", file.name)
xhr.send(formData);
}
}
</script>
.dsnupload {
background-color: #fbc786;
color: white;
text-align: center;
font-weight: bold;
padding: 20px;
}
.dsnupload:hover {
background-color: #c88f5c;
color: white;
font-weight: bold;
text-align: center;
}
<div class="row" style="margin-right: 10px;">
<form action="audio" method="post" enctype="multipart/form-data">
{% csrf_token %^}
{{ form }}
<button type="submit" class="dsnupload" id="audio-file" onchange="fileAdded()">
<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>
i have website with button to upload audio mp3 on a post. the problem, when i clicked the button, it's open new / (http://localhost:8000/audio) actually just http://localhost:8000. and when i see terimal, there's error message
Forbidden (CSRF token missing or incorrect.): /audio
at the same time, there's error at my website with error message
Forbidden (403) CSRF verification failed. Request aborted.
Help Reason given for failure:
CSRF token missing or incorrect.
In general, this can occur when there is a genuine Cross Site Request Forgery, or when Django's CSRF mechanism has not been used
correctly. For POST forms, you need to ensure:Your browser is accepting cookies. The view function passes a request
to the template's render method. In the template, there is a {%
csrf_token %} template tag inside each POST form that targets an
internal URL. If you are not using CsrfViewMiddleware, then you must
use csrf_protect on any views that use the csrf_token template tag, as
well as those that accept the POST data. The form has a valid CSRF
token. After logging in in another browser tab or hitting the back
button after a login, you may need to reload the page with the form,
because the token is rotated after a login. You're seeing the help
section of this page because you have DEBUG = True in your Django
settings file. Change that to False, and only the initial error
message will be displayed.You can customize this page using the CSRF_FAILURE_VIEW setting.
what i want is, i can upload file song mp3 with django without database (just local). and the song can be defined by information such as artist, duration, genre, etc.
and here's my code:
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
from django.conf.urls.static import static
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^decode/
views.py:
from django.http import HttpResponse
from django.shortcuts import render
from django.views.decorators.csrf import ensure_csrf_cookie
from subprocess import call
from django.core.files import File
from django.views.decorators.csrf import csrf_exempt
import subprocess
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')
#@csrf_exempt
def obfuscate(request):
print("HI")
if request.method == 'GET':
return HttpResponse("Hi")
if request.method == 'POST':
print("files: " + str(request.FILES))
print("posts: " + str(request.POST))
if len(request.POST) > 0:
handle_uploaded_file(request.FILES['audio_file'])
return HttpResponse("The form was valid!")
def handle_uploaded_file(f):
with open('temp.mp3', 'wb+') as destination:
for chunk in f.chunks():
destination.write(chunk)
subprocess.check_call("ffmpeg -y -i temp.mp3 temp.wav", shell=True)
def Audio_store(request):
if request.method == 'POST':
form = AudioForm(request.POST, request.FILES or None)
if form.is_valid():
form.save()
return HttpResponse('SUKSES BRUH')
else:
form = AudioForm()
return render(request, 'homepage.html', {'form' : form})
models.py:
from django import forms
from django.db import models
class Audio_store(models.Model):
record=models.FileField(upload_to='media/mp3')
class Meta:
db_table='Audio_store'
forms.py:
from django import forms
from MusicLockApp.models import *
class AudioForm(forms.ModelForm):
class Meta:
model=Audio_store
fields=['record']
add settings.py:
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 = '/mp3/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'mp3')
homepage.html script:
<script>
var file = undefined;
var audio_formats = ["mp3"];
// using jQuery
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
function fileAdded() {
var x = document.getElementById("audio-file");
file = x.files[0];
var msg = document.getElementById("message");
if (file != undefined) {
x = file.name.split(".");
var ext = x[x.length - 1];
if (audio_formats.indexOf(ext) == -1) {
msg.innerHTML = ext + " is not an audio file!";
} else {
msg.innerHTML = file.name + " has been successfully added!";
}
} else {
msg.innerHTML = "Please select an audio file to obfuscate!";
}
}
function obfuscate() {
if (file == undefined)
alert("Choose an audio file!");
else {
var obfuscateButton = document.getElementById("obfuscate-button");
obfuscateButton.innerHTML = "Proccessing...";
var xhr = new XMLHttpRequest();
var url = "http://127.0.0.1:8000/obfuscator/obfuscate/";
var method = 'POST';
xhr.onreadystatechange = function() {
if(xhr.readyState === 4 && xhr.status === 200) {
obfuscateButton.innerHTML = "Done!"
}
}
xhr.open(method, url, true);
xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
var formData = new FormData();
formData.append("audio_file", file);
formData.append("file_name", file.name)
xhr.send(formData);
}
}
</script>
.dsnupload {
background-color: #fbc786;
color: white;
text-align: center;
font-weight: bold;
padding: 20px;
}
.dsnupload:hover {
background-color: #c88f5c;
color: white;
font-weight: bold;
text-align: center;
}
<div class="row" style="margin-right: 10px;">
<form action="audio" method="post" enctype="multipart/form-data">
{% csrf_token %^}
{{ form }}
<button type="submit" class="dsnupload" id="audio-file" onchange="fileAdded()">
<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>
, views.decode),
url(r'^
views.py:
models.py:
forms.py:
add settings.py:
homepage.html script:
, views.homepage),
path('audio', views.Audio_store),
]
urlpatterns += staticfiles_urlpatterns()
views.py:
models.py:
forms.py:
add settings.py:
homepage.html script:
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论