Search code examples
htmldjangodjango-viewscsrf

Getting Django CSRF error with raw html form


I'm trying to set up a raw html form where a user can make a suggestion and then save it on a database with a POST method, but I keep getting a Forbidden (403) CSRF verification failed. Request aborted. even after following the steps in the Help section.

I have found that I don't get the error if I add csrf_exempt on top of my view like this:

from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def suggest_ptags(request):
    context = {}
    print("Form is submitted.")
    return render(request, "partials/search_form.html", context)

But I was made aware that It removes completly the CSRF protection and I don't want that.

So what should I do?

Here's my search_form.html form in a partials folder in templates:

<!-- Suggestion Form in popup -->
    <div class="prop-modal">
        <div class="prop-content">

            <a class="btn-close-prop">&times;</a>
            <img src="{% static 'images/pyramids.svg' %}">

            <form action="/suggest_ptags/" class="feedback-form" method="POST" enctype="text/plain">
            {% csrf_token %}
                    <h5 class="title-prop">Suggestion</h5>
                    <input class="input-prop" name="suggest" rows="3" cols="37" placeholder="suggest something..."></input>
                    <input class="button-prop" type="submit" value="Envoyez"></input>
            </form>

        </div>
    </div>

My current Views.py:

from django.views.decorators.csrf import ensure_csrf_cookie


@ensure_csrf_cookie
def suggest_ptags(request):
    context = {}
    print("Form is submitted.")
    return render(request, "partials/search_form.html", context)

And in my Urls:

from django.conf.urls import url
from django.contrib import admin
from search.views import HomeView, ProductView, FacetedSearchView, autocomplete, suggest_ptags
from .settings import MEDIA_ROOT, MEDIA_URL
from django.conf.urls.static import static

urlpatterns = [
    url(r'^$', HomeView.as_view(), name='home'),
    url(r'^admin/', admin.site.urls),
    url(r'^suggest_ptags/$', suggest_ptags, name='suggest_ptags'), #Suggestions
    url(r'^product/(?P<slug>[\w-]+)/$', ProductView.as_view(), name='product'),
    url(r'^search/autocomplete/$', autocomplete),
    url(r'^search/', FacetedSearchView.as_view(), name='haystack_search'),

] + static(MEDIA_URL, document_root=MEDIA_ROOT)

Any solutions?


Solution

  • You shouldn't use enctype="text/plain". You can remove it (which is the same as enctype="multipart/form-data"), or use enctype="multipart/form-data" if you are uploading files.