首页 > 解决方案 > 将 J Query datepicker 添加到 django 表单

问题描述

所以我一直试图在我的 django 代码中添加一个 J Query datepicker(日历的东西)大约一周,但我无处可去。我一直在尝试很多教程都无济于事 - 所以我需要一些帮助。我对 django 很陌生,但我的工作需要我将此日期选择器添加到站点。

这是我的forms.py:

class AnimalForm(forms.ModelForm):
    class Meta:
        model = Animal
        fields = ['animal_id','species_strain','dob', 'dod', 'sex', 'source', 'parents', 'labloc', 'notes']
        widgets ={
                    'dob':forms.DateInput(attrs={'class':'datepicker'}),
                    "dod":forms.SelectDateWidget(empty_label=("Choose Year", "Choose Month", "Choose Day")),
                    "parents":SelectMultiple(),
        }

这是我的views.py:

def addAnimal(request):
if request.method =='POST':
    aform = forms.AnimalForm(request.POST,request.FILES)
    aform.fields['dob'].widget.attrs.update({'class': 'datepicker'})
    aform.fields['dod'].widget.attrs.update({'class': 'datepicker'})
    if aform.is_valid():
        animal = aform.save(commit=False)
        animal.save()
        return redirect('/input')
else:
    aform = forms.AnimalForm()
return render(request, 'lab/input.html', {'aform':aform})

最后,这是我的 html 模板:

  <!-- date picker html -->
<script src="jquery-3.3.1.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$(function() {
$( "#dob" ).datepicker({
  changeMonth: true,
  changeYear: true,
  showButtonPanel: true,
 });
} );
</script>

我希望这是有道理的,根据我一直在做的教程,一切都应该是正确的,但老实说我不知道​​。我诚然不知道自己在做什么,但我别无选择,哈哈。我正在尝试在他们的网站上使用 J Query 日期选择器,老实说,我不知道出了什么问题。请帮忙

标签: jquerydjangodatepickerdjango-formscalendar

解决方案


推荐阅读