4

我试图从用户那里获取日期时间输入,但日期输入的数据类型被设置为 type="text"

以下是代码片段:

模板:

<link href="https://cdnjs.cloudflare.com/ajax/libs/jquery-datetimepicker/2.5.20/jquery.datetimepicker.min.css" integrity="sha256-DOS9W6NR+NFe1fUhEE0PGKY/fubbUCnOfTje2JMDw3Y=" crossorigin="anonymous" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-datetimepicker/2.5.20/jquery.datetimepicker.full.min.js" integrity="sha256-FEqEelWI3WouFOo2VWP/uJfs1y8KJ++FLh2Lbqc8SJk=" crossorigin="anonymous"></script>


<form method="POST" enctype="multipart/form-data">
    {% csrf_token %}
    {{form.stayFrom}}
    <script>
         $(function () {
         $("#id_stayFrom").datetimepicker({
             format: 'd/m/y',
             });
         });
      </script>
</form>

表格.py:

class RoomApplicationForm(forms.ModelForm):
    stayFrom = forms.DateTimeField(input_formats=['%d/%m/%y'])
    class Meta:
        model = Stay 
        fields = ('stayFrom')

模型.py:

class Stay(models.Model):
    user = models.OneToOneField(Account, on_delete=models.CASCADE, primary_key = True)

    stayFrom = models.DateTimeField(verbose_name="stay start date")

继承人呈现的html:

<input type="text" name="stayFrom" id="id_stayFrom" autocomplete="off">

你能指出我的代码中缺少什么吗?

4

2 回答 2

2

DateTimeField的默认小部件是文本字段 ( DateTimeInput )。所以这是预期的行为。

于 2020-02-25T07:55:29.883 回答
0

代替:

stayFrom = forms.DateTimeField(input_formats=['%d/%m/%y'])

做:

stayFrom = forms.CharField(widget=forms.TextInput(attrs={'type':'date'}))
于 2021-10-14T19:51:30.493 回答