首页 > 解决方案 > 在 Django View to template 中,我的日期总是以缩写月份、DD、yyyy 的形式出现,但 datepicker 会生成 MM/DD/YYYY

问题描述

我有一个简单的视图功能:

def booking_request_list(request):
    #filter between dates...
    #or filter if new bookings.. (is booked = false) AND A DATE
    room_list = Room.objects.all()
    object_list = HousingRequest.objects.all()

    return render(request, 'housing/housing_requests_lists.html', {'booked_list':object_list, 'room_list':room_list})

然后在我的模板中,我只显示这样的部分:

<table class="table">      
        <tr>           
            <th>Check In Date</th>           
        </tr>
        {% for hou in not_booked_list %}
        <tr value={{hou.pk}}>
             <td> {{hou.checkin_date}} </td>   <td><input type="text" value="{{ hou.checkin_date}}" name="checkin_date_{{hou.pk}}" data-date-format="M/dd/yyyy" class="datepicker form-control dateinput form-control" tabindex="6" autocomplete="off" required id="id_checkin_date_{{hou.pk}}" bid="{{hou.pk}}"></td>
        </tr>
        {% endfor %}
      </table>

base.html 在 html 文件的末尾有这部分

 <script type="text/javascript">


            $(function() {
              var j = jQuery.noConflict();    
              j('.dateinput').datepicker({ format: "yyyy/dd/M" });
            });
          </script>
    </body>
    </html>

但似乎日期选择器根本不尊重它。

例如显示的日期是:

2019 年 11 月 11 日

在数据库中,它存储为YYYY-MM-DD

模型的定义是:

class HousingRequest(models.Model):
    objects = models.Manager()

    room = models.ForeignKey('Room', null=True, blank=True, on_delete=models.CASCADE)
    user = models.ForeignKey('accounts.APOUser', on_delete=models.CASCADE)
    checkin_date = models.DateField('checkin date')

这在表单首次加载时效果很好,但是当用户点击日期选择器并选择一个日期然后在输入框中输入时:

月/日/年

I tried above to set the format of the date picker via the data tag and it doesn't seem to take. I also don't know how to just force the date from django in the view to be MM/DD/YYYY (making it work like the date picker since the data setting doesn't seem to work). I can even just display the date:

<td> {{hou.checkin_date}}</td>  

And it still displays it as abbreviated month day, year I don't really care the displayed format but I just want it to be consistent between what is loaded and what the date picker puts. (With the knowledge to have more power/control in the future of my dates look and feel)

So not sure if it is a django configuration (I tried this in my settings file, not knowing if this was even right:

 DATE_FORMAT = {
    '%m/%d/%Y'
}

Or is it some more code in my view when I retrieve the record I need? Or do I have play with the datepicker still, which is a bootstrap4 datepicker I believe.

标签: djangodatepicker

解决方案


Try formatting the date as follows:

<script> 
$('#datepicker1').datepicker({ format: 'yyyy-mm-dd', uiLibrary: 'bootstrap4' });
</script>

推荐阅读