I have a model where an object is called time which is model.DateTimeField(default=datetime.now)
I also have a form where the user can specify the time, but I wanted to only have the H: M in there, not the whole datetime.
I tried using the TimeInput widget in my form, but that would give me an error upon submitting because I didn't have the 'date' portion of the DateTimeField. If I use models.TimeField for time, I lose the ability to keep track of the date in the admin page.
How can I hide the date from showing in my form?
Worked around the problem by having one model as DateTimeField and another as TimeField.
Related
i am making this app in django where on a particular html template if the user selects a particular response by clicking on it, the date and time at which the user clicked that particular response is stored in my database.
part of models.py
class userresp(models.Model):
rid=models.Integerfield(unique=True,default=0)
uid=models.Foreignkey(user,to_field='uid',on_delete=models.CASCADE)
resp=models.ForeignKey(elementsound,to_field='csid',on_delete=models.CASCADE)
date=models.DateTimeField()
time=models.DateTimeField()
so how do i store that? and what will be the extra parameters in the DateTimeField of both?
You can do the what you require inside a View by overriding the post() method.
To store the user's response time, you can make use of django's builtin timezone module.
So you just need to do:
from django.utils import timezone
date_and_time = timezone.now()
timezone.now() returns the system date and time of the server.
And by the way, you don't need two 'DateTimeField's to store the date and time. One is enough, it can store both the date and time.
Otherwise you can just get the current date and time at the time of userresp object creation.
class userresp(models.Model):
rid=models.Integerfield(unique=True,default=0)
uid=models.Foreignkey(user,to_field='uid',on_delete=models.CASCADE)
resp=models.ForeignKey(elementsound,
to_field='csid',
on_delete=models.CASCADE)
date_and_time=models.DateTimeField(auto_now_add=True)
I'm using a formset to update a single field of a large group of model instances. I'd like to display a time stamp showing the time since the field for that instance was last updated. Since this field will usually be updated once a week, I'd rather use a DateField than a DateTimeField for the time stamp. DateField doesn't seem to get updated on save though. When I change the model field to DateTimeField, however, it works as expected. Here's my code.
#Template
<div class = 'last-updated'> {{ form.instance.last_updated|timesince }} </div>
# Models.py
last_updated = models.DateField(auto_now=True)
# Models.py - This version works
last_updated = models.DateTimeField(auto_now=True)
I've found posts saying to override the model's save() method but this seems like a last resort, and the posts I've found saying this are dated from 2011 and earlier, so probably out of date.
Since the docs list DateField and DateTimeField as more or less the same, with the same optional arguments, I'm wondering why they don't seem to update auto_now in the same way.
Edit
It also looks as though when I change the field type to DateField, the value displayed is the time since creation, not the time since update, and it updates the value for every single item in the formset. To clarify, there is NO custom save method for this model.
When I post a time with timezone information eg:2013-02-27T14:00:00-05:00 to a Django datetime field throws a form error "Enter a valid date/time.".
My form field is defined as below
time = forms.DateTimeField()
I also tried passing in date formats to the form filed. eg:
DATE_FORMATS = [
'%Y-%m-%dT%H:%M:%S-%z',
]
time = forms.DateTimeField(input_formats=DATE_FORMATS)
Does Django DateTimeField not support time with timezone information?
Yes! Django DateTimeField supports timezones, but if you take a look at the documentation, you have to specify it separately from the actual DateTime in your form. Specifically, the documentation recommends that you activate a timezone on a per user basis, otherwise you will always end up entering the DateTime in the default timezone.
https://docs.djangoproject.com/en/dev/topics/i18n/timezones/#time-zone-aware-input-in-forms
This is the documentation I used for my project, and it worked out well.
In addition, if you need to specify a specific timezone in a form field, you can always create a drop down field with all of the timezones in it, and then save the DateTime in your view with the correct timezone.
I built a form in django and I'm having trouble debugging my Tours Choices. It is a ChoiceField and I use the CheckboxMultipleSelect Widget. I don't know what I'm doing wrong to get the error in the screenshot below. Any thoughts? Do I need to facilitate more information? I'm a django newbie.
Picture of the Form Error
A form.ChoiceField lets you input exactly one choice for a form (out of a selection of several choices). If you saved it to a database in a model there would be one value stored in the database. Your CheckboxMultipleSelect widget is for a form.MultipleChoiceField where you can input multiple values. So change your ChoiceField to a MultipleChoiceField in your form and you should be fine. If you save this data to a model, that model would have to be an appropriate field, like a ManyToManyField if they are Foreign Keys.
Greetings,
I am trying to implement a TimeField model which only consists of HH:MM (ie 16:46) format, I know it is possible to format a regular Python time object but I am lost about how to manage this with Django.
Cheers
Django widget can be used to achieve this easily.
from django import forms
class timeSlotForm(forms.Form):
from_time = forms.TimeField(widget=forms.TimeInput(format='%H:%M'))
DateTime fields will always store also seconds; however, you can easily tell the template to just show the hours and minute, with the time filter:
{{ value|time:"H:M" }}
where "value" is the variable containing the datetime field.
Of course, you can also resort to other tricks, like cutting out the seconds from the field while saving; it would require just a small change to the code in the view handling the form, to do something like this:
if form.is_valid():
instance = form.save(commit=False)
instance.nosecs = instance.nosecs.strptime(instance.nosecs.strftime("%H:%M"), "%H:%M")
instance.save()
(note: this is an ugly and untested code, just to give the idea!)
Finally, you should note that the admin will still display the seconds in the field.
It should not be a big concern, though, because admin should be only used by a kind of users that can be instructed not to use that part of the field.
In case you want to patch also the admin, you can still assign your own widget to the form, and thus having the admin using it. Of course, this would mean a significant additional effort.
So I think the proposed and accepted solution is not optimal because with:
datetime.widget = forms.SplitDateTimeWidget(time_format=('%H:%M'))
For a SplitDateTimeField in my case but for you only change it to TimeWidget.
Hope it helps other people too.
TimeField model
in Template
Is displayed
{{ value|time:"H:i" }}
Is not displayed
{{ value|time:"H:M" }}
Django 1.4.1
For a ModelForm, you can easily add a widget like this, to avoid the seconds being shown (just show hh:mm):
class MyCreateForm(forms.ModelForm):
class Meta:
model = MyModel
fields = ('time_in', 'time_out', )
widgets = {
'time_in': forms.TimeInput(format='%H:%M'),
'time_out': forms.TimeInput(format='%H:%M'),
}
You can at least modify the output in the __str__ method on the model by using datetime.time.isoformat(timespec='minutes'), like this:
def __str__(self):
return self.value.isoformat(timespec='minutes')
Now the value is showing as HH:MM in admin pages.
On Django 1.9 the following format should work:
{{ yourData.value|time:"H:i" }}
Django has a whole set of template tags and filters.
Django 1.9 documentation on this is:
https://docs.djangoproject.com/en/1.9/ref/templates/builtins/#time