使用templateView django中的发布请求发送数据



我正在使用 Django 2.0

我有一个TemplateView仅呈现模板。由于模板是使用ajax渲染的,因此我必须使用POST将令牌发送到LearnQuestion只是为了验证,并且不需要形式。

我尝试关注

案例1:

views.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)

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();
    });
});

但这给出了错误

Forbidden (CSRF token missing or incorrect.): /learn/q/63aa909f-ffb4-462e-bdcc-018bc71d35d2

案例2:

在模板中使用<form>相同的视图

<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();
    });
});

这给出了错误

Method Not Allowed (POST): /learn/q/63aa909f-ffb4-462e-bdcc-018bc71d35d2

案例3: 将TemplateView更改为FormView,并在 forms.py

中创建了一个表单

forms.py

class SessionForm(forms.Form):
    session = forms.CharField()

views.py

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

但这给出了错误

django.core.exceptions.ImproperlyConfigured: No URL to redirect to. Provide a success_url.

,但我不想要重定向的URL。

如何将POST请求发送到TemplateView或不用redirect_urlFormView

我不希望形式处理程序只想使用Ajax发送发布数据以查看

您也可以通过javascript生成 CSRF_TOKEN ,以发送其发送给Ajax的请求。

// 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');

现在,当您通过Ajax发送数据时,您可以使用此CSRFTOKEN

var csrftoken = Cookies.get('csrftoken');

来源:https://docs.djangoproject.com/en/2.0/ref/csrf/#ajax

我们可以通过@king Reload在此处回答的AJAX请求中的csrf_token作为header

headers:{
    "X-CSRFToken": '{{ csrf_token }}'
},

最新更新