'Forbidden (CSRF token missing or incorrect.): /

So i want to make models form to upload file mp3. I was copy the code from website, but suddenly it goes error. Here's error message on the website :

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.

and at my terminal there's error message :

[12/May/2022 14:19:43] "GET / HTTP/1.1" 200 8824 Forbidden (CSRF token missing or incorrect.): / [12/May/2022 14:19:46] "POST / HTTP/1.1" 403 2513

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.

website

console

folder

error



Solution 1:[1]

Easiest way

Try to change this url url(r'^$', views.homepage), in your urls.py file to this url(r'^$', views.upload),

Effective way

Or instead of that, delete your " homepage " view and rename your " upload " view to " homepage ".

Then check if it work. You'll normally see a form appear in your webpage to select your file.

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