我正在研究django-floppyforms的实现,特别是slider widget。但是我不能让它显示在我的django Web应用程序中。原生滑块可以工作,但jQuery滑块不会。下图显示了问题。
错误
> UserWarning: A {% csrf_token %} was used in a template, but the
> context did not provide the value. This is usually caused by not
> using RequestContext. warnings.warn("A {% csrf_token %} was used in
> a template, but the context did not provide the value. This is
> usually caused by not using RequestContext.")
This Question,this question,and this question都建议确保使用django.core.context_processors.csrf
上下文处理器,其中一个解决方案是使用RequestContext
来自{ {1}}
正如你在下面所见,我试图实现它,但它一直给我同样的错误。
有什么想法吗?
views.py
django.template
slider_one.html
def sview(request):
jquery_slider = Slider()
native_slider = SlideForm()
return render_to_response('slider_one.html', {
'jquery_slider': jquery_slider,
'native_slider': native_slider,
}, context_instance=RequestContext(request))
forms.py
{# slider.html #}
{% include "floppyforms/input.html" %}
<div id="{{ attrs.id }}-slider"></div>
<html>
<body>
<h1>This is your slider_one.html template</h1>
<script type="text/javascript" src="{{ STATIC_URL }}/js/jquery.min.js"></script>
<script type="text/javascript" src="{{ STATIC_URL }}/js/jquery-ui.min.js"></script>
<script type="text/javascript" src="{{ STATIC_URL }}/css/jquery-ui.min.css"></script>
<form action="" method="post">
{% csrf_token %}
{{ jquery_slider }}
{{ native_slider }}
<input type="submit" value="Submit" />
</form>
<script type="text/javascript">
$(document).ready(function() {
var type = $('<input type="range" />').attr('type');
if (type == 'text') { // No HTML5 support
$('#{{ attrs.id }}').attr("readonly", true);
$('#{{ attrs.id }}-slider').slider({
{% if value %}value: {{ value }},{% endif %}
min: {{ attrs.min }},
max: {{ attrs.max }},
step: {{ attrs.step }},
slide: function(event, ui) {
$('#{{ attrs.id }}').val(ui.value);
}
});
}
});
</script>
编辑:
我在settings.py文件的MIDDLEWARE_CLASSES中也启用了以下功能
import floppyforms as forms
class Slider(forms.RangeInput):
min = 5
max = 20
step = 5
template_name = 'slider_one.html'
class Media:
js = (
'/static/js/jquery.min.js',
'/static/js/jquery-ui.min.js',
)
css = {
'all': (
'/static/css/jquery-ui.css',
)
}
class SlideForm(forms.Form):
num = forms.IntegerField(widget=Slider)
def clean_num(self):
num = self.cleaned_data['num']
if not 5 <= num <= 20:
raise forms.ValidationError("Enter a value between 5 and 20")
if not num % 5 == 0:
raise forms.ValidationError("Enter a multiple of 5")
return num
答案 0 :(得分:1)
我遇到了同样的问题。正如@professorDante所说,你需要:
T
关键是必须将请求对象传递给模板才能生成csrf。
答案 1 :(得分:0)
尝试使用render()快捷方式 - 您希望使用RequestContext,并且该方法默认使用一个。如果它有效,你知道它是你的return_to_render的实现。
from django.shortcuts import render
return render(request, "slider_one.html",{'jquery_slider':jquery_slider,'native_slider':native_slider})