使用原始HTML表单获取Django CSRF错误

时间:2019-05-16 20:37:26

标签: html django django-views csrf

我正在尝试建立一个原始的html表单,用户可以在其中提出建议,然后使用POST方法将其保存在数据库中,但是即使按照以下步骤操作,我仍然会收到Forbidden (403) CSRF verification failed. Request aborted.帮助部分。

我发现,如果像这样在视图上方添加csrf_exempt,我不会收到错误消息:

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)

但是我意识到它完全删除了CSRF保护,我不希望这样做。

那我该怎么办?

这是我的search_form.html表单,位于模板的partials文件夹中:

<!-- 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>

我当前的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)

在我的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)

有解决方案吗?

1 个答案:

答案 0 :(得分:1)

您不应使用enctype="text/plain"。您可以将其删除(与enctype="multipart/form-data"相同),如果要上传文件,则可以使用enctype="multipart/form-data"