Reputation: 541
Hi guys I'm trying to pre-populate a date time field when my user opens the form. I need to display the datetime
field too as the user may need to change it.
I've tried using initial={'trans_date': 'insert date here'}
but can't manage to get it to work, and I would assume i would need to input a datetime
variable into too.
Any help would be greatly appreciated.
trans.html
{% include 'head.html' %}
{% include 'navbar.html' %}
<div class="container">
Input Data
<form method='POST' action=''>{% csrf_token %}
{{ form.as_p }}
<input type="submit" class="btn pull-right btn-success col-sm-5" value="Submit">
</form>
</div>
views.py
def home(request):
form = TransactionForm(request.POST or None)
if form.is_valid():
save_it = form.save(commit=False)
save_it.save()
return HttpResponseRedirect('/transactions/')
return render_to_response("trans/trans.html", locals(), context_instance=RequestContext(request))
forms.py
from django import forms
from bootstrap3_datetime.widgets import DateTimePicker
from .models import Transaction
import datetime
class TransactionForm(forms.ModelForm):
class Meta:
model = Transaction
exclude = ['ip']
labels = {
'amount':'Amount',
'trans_date':'Date of Transaction'
}
widgets = {
'trans_date': DateTimePicker(options={"format": "YYYY-MM-DD HH:mm", "pickSeconds": False},
attrs={"placeholder": "Placeholder text"},),
}
#fields = "__all__"
#fields = ['for_you', 'first_name', 'last_name', 'email']
models.py
class Transaction(models.Model):
trans_date = models.DateTimeField(auto_now=False, auto_now_add=False)
trans_type = models.CharField(max_length=120, null=True, blank=True)
category = models.ManyToManyField(Category)
amount = models.IntegerField()
description = models.TextField(null=True, blank=True)
timestamp = models.DateField(auto_now_add=True, auto_now=False)
updated = models.DateField(auto_now_add=False, auto_now=True)
ip = models.CharField(max_length=250, blank=True, null=True)
def __unicode__(self):
return smart_unicode(self.trans_type)
Upvotes: 1
Views: 2139
Reputation: 3018
In your form init method
def __init__(self, *args, **kwargs):
super(TransactionForm, self).__init__(*args, **kwargs)
self.fields['trans_date'].initial = #pre populated field.
This will render the form with the new date, when the form save it will be updated in the model.
Upvotes: 1