在TemplateView Django中使用POST请求发送数据

在TemplateView Django中使用POST请求发送数据,django,django-forms,Django,Django Forms,我正在使用Django 2.0 我有一个TemplateView,它只呈现模板。由于模板是使用ajax呈现的,因此我必须使用POST将令牌发送到LearnQuestion进行验证,而不需要表单 我试着跟着 案例1: 视图.py class LearnQuestion(TemplateView): # form_class = SessionForm template_name = 'learn/learn_question.html' def get_context_d

我正在使用Django 2.0

我有一个
TemplateView
,它只呈现模板。由于模板是使用
ajax
呈现的,因此我必须使用
POST
将令牌发送到
LearnQuestion
进行验证,而不需要表单

我试着跟着

案例1:

视图.py

class LearnQuestion(TemplateView):
    # form_class = SessionForm
    template_name = 'learn/learn_question.html'

    def get_context_data(self, **kwargs):
        context = super(LearnQuestion, self).get_context_data(**kwargs)

        # get session data
        session = self.request.POST.get('session')
        print(session)
        context['session'] = session

        return context

    @method_decorator(login_required)
    def dispatch(self, request, *args, **kwargs):
        return super(self.__class__, self).dispatch(request, *args, **kwargs)
class SessionForm(forms.Form):
    session = forms.CharField()
class LearnQuestion(FormView):
    form_class = SessionForm
    template_name = 'learn/learn_question.html'
    ...
    ...
Ajaxrequest

<input id="session-d" value="{{ session }}" type="hidden">

$(window).on('load', function() {
    console.log($('#session-id').val())
    $('#question-box').load("{% url 'learn:question' course_learn.pk %}", {session:$('#session-id').val()}, function(){
        runTimer();
    });
});
案例2:

与模板中的
视图相同

<form id="sesion-form">
    {% csrf_token %}
    <input id="session-d" value="{{ session }}" type="hidden">
</form>

$(window).on('load', function() {
    console.log($('#session-id').val())
    $('#question-box').load("{% url 'learn:question' course_learn.pk %}", $('#session-form').serializeArray(), function(){
        runTimer();
    });
});
案例3: 将
TemplateView
更改为
FormView
,并在forms.py中创建了一个表单

class LearnQuestion(TemplateView):
    # form_class = SessionForm
    template_name = 'learn/learn_question.html'

    def get_context_data(self, **kwargs):
        context = super(LearnQuestion, self).get_context_data(**kwargs)

        # get session data
        session = self.request.POST.get('session')
        print(session)
        context['session'] = session

        return context

    @method_decorator(login_required)
    def dispatch(self, request, *args, **kwargs):
        return super(self.__class__, self).dispatch(request, *args, **kwargs)
class SessionForm(forms.Form):
    session = forms.CharField()
class LearnQuestion(FormView):
    form_class = SessionForm
    template_name = 'learn/learn_question.html'
    ...
    ...
forms.py

class LearnQuestion(TemplateView):
    # form_class = SessionForm
    template_name = 'learn/learn_question.html'

    def get_context_data(self, **kwargs):
        context = super(LearnQuestion, self).get_context_data(**kwargs)

        # get session data
        session = self.request.POST.get('session')
        print(session)
        context['session'] = session

        return context

    @method_decorator(login_required)
    def dispatch(self, request, *args, **kwargs):
        return super(self.__class__, self).dispatch(request, *args, **kwargs)
class SessionForm(forms.Form):
    session = forms.CharField()
class LearnQuestion(FormView):
    form_class = SessionForm
    template_name = 'learn/learn_question.html'
    ...
    ...
视图.py

class LearnQuestion(TemplateView):
    # form_class = SessionForm
    template_name = 'learn/learn_question.html'

    def get_context_data(self, **kwargs):
        context = super(LearnQuestion, self).get_context_data(**kwargs)

        # get session data
        session = self.request.POST.get('session')
        print(session)
        context['session'] = session

        return context

    @method_decorator(login_required)
    def dispatch(self, request, *args, **kwargs):
        return super(self.__class__, self).dispatch(request, *args, **kwargs)
class SessionForm(forms.Form):
    session = forms.CharField()
class LearnQuestion(FormView):
    form_class = SessionForm
    template_name = 'learn/learn_question.html'
    ...
    ...
但这会产生错误

Forbidden (CSRF token missing or incorrect.): /learn/q/63aa909f-ffb4-462e-bdcc-018bc71d35d2
Method Not Allowed (POST): /learn/q/63aa909f-ffb4-462e-bdcc-018bc71d35d2
django.core.exceptions.ImproperlyConfigured: No URL to redirect to. Provide a success_url.
但我不想要重定向url

我如何将
POST
请求发送到
TemplateView
或使用
FormView
而不使用
redirect\u url


我不希望表单处理程序只希望使用ajax发送POST数据以查看

您也可以通过Javascript生成csrf\u令牌,以便通过ajax将其发送到POST请求

// 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;
}
var csrftoken = getCookie('csrftoken');

来源:

我们可以将
csrf\u令牌
作为
传递到ajax请求中,由@King Reload回答


只是一个改进视图的提示:您可以使用而不是
方法\u decorator
。您必须使用POST发送令牌以进行验证,并且不需要表单。您将post请求发送到哪里?Lemayzeur,将post请求发送到
LearnQuestion
表单用于验证和显示。它们在Ajax中仍然很有用。请查看我关于如何将Ajax请求正确发送到后端的答案:@AnujTBE