看了this link并找到了一些帮助,但我想知道如何为我的models.py中的DateField选择使用JQueryUI Datepicker小部件
models.py
from django.db import models
class EModel(models.Model):
date = models.DateField(blank=False)
forms.py
from django import forms
from models import EModel
class EForm(forms.ModelForm):
class Meta:
model = EModel
form.html - Django如何呈现我的表单。 不在管理页面
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Form</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
</head>
<body>
<form action="" method="post">{% csrf_token %}
{{ form.date }} <!-- ***** -->
<!-- The rest of my form -->
</form>
</body>
我希望有一种方法可以让我的'date'模型字段渲染为JQueryUI Datepicker小部件,但我已经搜索过,发现无法链接这两个(在我的情况下)。
解
在我的forms.py
中from django import forms
from models import EModel
class EForm(forms.ModelForm):
class Meta:
model = EModel
widgets = {
'date' : forms.DateInput(attrs={'type':'date'})
}
答案 0 :(得分:9)
在模型表单中编辑日期窗口小部件属性,为其提供类&#39; .datepicker&#39;,以及JQuery datepicker将查找的内容。所以你的ModelForm变成了:
class EForm(forms.ModelForm):
class Meta:
model = EModel
widgets = {'date': DateInput(attrs={'class': 'datepicker'})}
文档here。
答案 1 :(得分:2)
我使用以下代码,它对我来说很好。我已经提到了这个项目的所有文件,
<强> models.py 强>
from django.db import models
class EModel(models.Model):
date = models.DateField(blank=False)
<强> forms.py 强>
from django import forms
from testApp.models import EModel
class EForm(forms.ModelForm):
class Meta:
model = EModel
widgets = {'date': forms.DateInput(attrs={'class': 'datepicker'})}
<强> form.html 强>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Form</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
<script>
$(function() {
$( "#id_date" ).datepicker();
});
</script>
</head>
<body>
<form action="/datepickerview/" method="post">{% csrf_token %}
<!--{{ form.date }} -->
<p>Date: <input name='date' type="text" id="id_date"></p>
<!-- The rest of my form -->
<input type="submit" value="login" />
</form>
</body>
<强> views.py 强>
from django.shortcuts import render
from django.http import HttpResponse
from django.template import Context
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django.core.context_processors import csrf
from django.template import RequestContext
from forms import EForm
def datepickerview(request):
# Get the context from the request.
context = RequestContext(request)
# A HTTP POST?
if request.method == 'POST':
form = EForm(request.POST)
# Have we been provided with a valid form?
if form.is_valid():
form.save(commit=True)
return HttpResponse("Successfully added the date to database");
else:
# The supplied form contained errors - just print them to the terminal.
print form.errors
else:
# If the request was not a POST, display the form to enter details.
form = EForm()
return render_to_response('form.html', {'form': form}, context)
<强> urls.py 强>
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^datepickerview/$', 'testApp.views.datepickerview'),
)
<强> admin.py 强>
from django.contrib import admin
from testApp.models import EModel
admin.site.register(EModel)
答案 2 :(得分:1)
最好的方法是在应用中的widgets.py文件中创建一个新的小部件:
以下是颜色选择器的一个例子:
- widgets.py -
from django import forms
from django.conf import settings
from django.utils.safestring import mark_safe
class ColorPickerWidget(forms.TextInput):
class Media:
css = {
'all': (
settings.STATIC_URL + 'colorpicker/css/colorpicker.css',
)
}
js = (
settings.STATIC_URL + 'js/jquery-1.8.3.min.js',
settings.STATIC_URL + 'colorpicker/js/colorpicker.js',
)
def __init__(self, language=None, attrs=None):
self.language = language or settings.LANGUAGE_CODE[:2]
super(ColorPickerWidget, self).__init__(attrs=attrs)
def render(self, name, value, attrs=None):
rendered = super(ColorPickerWidget, self).render(name, value, attrs)
return rendered + mark_safe(u'''
<script type="text/javascript">
jQuery('#id_%s').css("background-color", "#"+jQuery('#id_%s').val());
jQuery('#id_%s').ColorPicker({
onSubmit: function(hsb, hex, rgb, el) {
jQuery(el).val(hex);
jQuery(el).css("background-color", "#"+hex);
jQuery(el).ColorPickerHide();
},
onBeforeShow: function () {
code = this.value
if (code.length==3) code = code.charAt(0)+code.charAt(0)+code.charAt(1)+code.charAt(1)+code.charAt(2)+code.charAt(2);
jQuery(this).ColorPickerSetColor(code);
}
}).bind('keyup', function(){
el = jQuery(this);
code = el.val();
hex = '#'+code;
var isOk = /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(hex);
if (isOk) {
el.css("background-color", hex);
if (code.length==3) code = code.charAt(0)+code.charAt(0)+code.charAt(1)+code.charAt(1)+code.charAt(2)+code.charAt(2);
el.ColorPickerSetColor(code);
}
else if (code=="") el.css("background-color", "");
});
</script>
''' % (name, name, name))
--- views.py ---
from django import forms ColorPickerWidget
from myapp.widgets import
class EditBackgroundForm(forms.Form):
background = forms.CharField(max_length=10, widget= ColorPickerWidget(), required = False, label="Background color")
此外,您还可以使用小部件创建自定义表单字段,并覆盖其clean()
方法。