我正在研究 django-floppyforms 的实现,特别是滑块小部件。但是我无法让它显示在我的 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和this question都建议确保使用django.core.context_processors.csrf
上下文处理器,解决方案之一是使用RequestContext
fromdjango.template
正如您在下面看到的,我试图实现它,但它一直给我同样的错误。
有任何想法吗?
- Django==1.6.2
- django-floppyforms==1.2.0
视图.py
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))
slider_one.html
{# 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>
表格.py
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
编辑:
我还在我的 settings.py 文件的 MIDDLEWARE_CLASSES 中启用了以下功能
django.middleware.csrf.CsrfViewMiddleware'