Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - Setting date as date input value

I'm trying to set a date as the value of a date input in a form. But, as your may have guessed, it's not working.

Here's what I have in my template:

<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>

And this is the view that calls it as well as the Placement model:

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)

But it doesn't display the date. Just an empty date input...

How can I fix this?

Thanks!

like image 358
Pictraz Avatar asked Dec 01 '22 00:12

Pictraz


1 Answers

The HTML date should take the format YYYY-MM-DD. So you have to make a conversion using the {{ value|date:"D d M Y" }} command.

Your code will be:

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

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

Django date documentation here: https://docs.djangoproject.com/en/1.7/ref/templates/builtins/#date

like image 167
aberna Avatar answered Dec 05 '22 14:12

aberna