Django - 将日期设置为日期输入值

时间:2015-01-26 13:05:03

标签: python html django

我试图将日期设置为表单中日期输入的值。但是,正如你可能已经猜到的那样,它没有用。

这是我在模板中的内容:

<div class="form-group">
       <label for="date" class="col-md-3 control-label">Date</label>
    <div class="col-md-9">
        <input type="date" class="form-control" id="date" value="{{placement.date}}">
    </div>
</div>

这就是调用它以及Placement模型的视图:

class Placement(models.Model):
    student = models.ForeignKey(Student)
    email = models.EmailField(max_length=254)
    fname = models.CharField(max_length=50)
    sname = models.CharField(max_length=50)
    cname = models.CharField(max_length=100)
    position = models.CharField(max_length=50)
    house = models.CharField(max_length=50, blank=True)
    street = models.CharField(max_length=50)
    town = models.CharField(max_length=50)
    county = models.CharField(max_length=50)
    postcode = models.CharField(max_length=8)
    phone = models.CharField(max_length=20)
    length = models.IntegerField(null=True)
    category = models.CharField(max_length=50)
    date = models.DateField(null=True)
    confirmed = models.BooleanField(default=False)
    completed = models.BooleanField(default=False)
    created = models.DateTimeField(null=True)

def view_placement(request, placement_id):
    school = School.objects.get(pk=request.session['school'])
    context = {'school':school}
    if request.session['utype'] == 'a':
        context['user'] = Administrator.objects.get(pk=request.session['user'])
        context['placement'] = Placement.objects.get(pk=placement_id)
        return render(request, 'workxp/admin/view_placement.html', context)

但它没有显示日期。只是一个空日期输入...

我该如何解决这个问题?

谢谢!

3 个答案:

答案 0 :(得分:9)

HTML日期应采用YYYY-MM-DD格式。因此,您必须使用{{ value|date:"D d M Y" }}命令进行转换。

您的代码将是:

 <input type="date" class="form-control" id="date" value="{{placement.date|date:"Y-m-d" }}">

HTML文档:http://www.w3.org/TR/html-markup/input.date.html#input.date.attrs.value

Django日期文档:https://docs.djangoproject.com/en/1.7/ref/templates/builtins/#date

答案 1 :(得分:0)

在上面的答案中打了一个小错字-日期格式用双引号引起来,位于一组双引号中。应该在'Y-m-d'附近​​工作!

<input type="date" class="form-control" id="date" value="{{placement.date|date:"Y-m-d" }}">

应为:

<input type="date" class="form-control" id="date" value="{{placement.date|date:'Y-m-d' }}">

答案 2 :(得分:0)

您可以使用任何日期格式。

示例,在模板中使用{{ value|date:"SHORT_DATE_FORMAT" }}

from django.forms import DateField
from django.utils import formats
# need '%d.%m.%Y' instead of 'd.m.Y' from get_format()
dformat = ('.' + formats.get_format("SHORT_DATE_FORMAT", lang=request.LANGUAGE_CODE)).replace('.', '.%').replace('-', '-%').replace('/', '/%')[1:]
dfield = DateField(input_formats=(dformat,))
<date> = dfield.to_python(<string>)