我想用datepicker实现一个django表单。我制作了 forms.py
from django import forms
class DateRangeForm(forms.Form):
start_date = forms.DateField(widget=forms.TextInput(attrs=
{
'class':'datepicker'
}))
end_date = forms.DateField(widget=forms.TextInput(attrs=
{
'class':'datepicker'
}))
和 的 views.py
if request.method == "POST":
f = DateRangeForm(request.POST)
if f.is_valid():
c = f.save(commit = False)
c.end_date = timezone.now()
c.save()
else:
f = DateRangeForm()
args = {}
args.update(csrf(request))
args['form'] = f
return render(request, 'trial_balance.html', {
'form': f
})
balance.html
<div>
<form action="" method="POST"> {% csrf_token %}
Start Date:{{ form.start_date }} End Date:{{ form.end_date }}<br/>
<input type = "submit" name = "submit" value = "See Results">
</form>
</div>
我的输入框中仍然没有该日期选择器。 我还尝试在脚本中包含我的文件链接,如我的balance.html
<script src="{{ STATIC_URL }}js/jquery-1.3.2.min.js"></script>
仍然是日期选择器不起作用。但是当我在我的html文件中包含jquery时,它也不会使我在html文件中实现的jquery-treetable工作。
如何使日期选择器工作?
答案 0 :(得分:32)
您可以使用forms.DateInput()
小部件,而不是forms.TextInput()
:
from functools import partial
DateInput = partial(forms.DateInput, {'class': 'datepicker'})
class DateRangeForm(forms.Form):
start_date = forms.DateField(widget=DateInput())
end_date = forms.DateField(widget=DateInput())
要使JQuery Datepicker正常工作,您必须对其进行初始化:
<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.0/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.11.0/jquery-ui.js"></script>
<script>
$(document).ready(function() {
$('.datepicker').datepicker();
});
</script>
答案 1 :(得分:0)
下面的示例使用Django的generic.CreateView:
models.py文件
class Task(models.Model):
task_due_date = models.DateField()
views.py文件
from bootstrap_datepicker_plus import DatePickerInput
class add_task(LoginRequiredMixin,generic.CreateView):
model = Task
fields = '__all__'
def get_form(self):
form = super().get_form()
form.fields['task_due_date'].widget = DatePickerInput()
return form
template_name = 'team/add_task.html'
templates / add_task.html
{% extends 'base.html' %}
{% load bootstrap4 %}
{% block body %}
{% bootstrap_javascript jquery='full' %}
{{ form.media }}
<h1>Add a Task</h1>
<br>
<div class="container">
<div class="row">
<form method="POST" action="{% url 'team:add_task' %}" id="taskForm">
{% csrf_token %}
{% bootstrap_form form %}
{% buttons %}
<button type="submit" class="btn btn-primary btn-large">Add</button>
{% endbuttons %}
</form>
</div>
</div>
{% endblock %}
最终结果是: