我正在使用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.
但我不想要重定向网址。
如何在没有POST
的情况下向TemplateView
发送FormView
个请求或使用redirect_url
?
我不希望表单处理程序只想使用ajax发送POST数据来查看
答案 0 :(得分:0)
您也可以通过Javascript生成 csrf_token ,以便通过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');
现在,当您通过ajax发送数据时,您可以使用此csrftoken
var csrftoken = Cookies.get('csrftoken');
答案 1 :(得分:0)
我们可以将csrf_token
作为header
传递给ajax请求,并由@King Reload here
headers:{
"X-CSRFToken": '{{ csrf_token }}'
},