简体   繁体   中英

Removing the seconds from a Django TimeField when a user is editing the form field

I have a model that's called Event where a user can add an event_name, event_time, and event_location.

The event_time is a Django Timefield

The user can also edit the time as they see fit. However, when I let the user edit the field, the field shows up like this:

10:00:00

I know that this is how it's stored internally, but is there way to remove the seconds when the user edits the field? Like this :

10:00

Forms.py:

time_widget = forms.widgets.TimeInput(attrs={'class': 'form-control', 'placeholder': 'ex: 10:30AM'})
valid_time_formats = ['%H:%M', '%I:%M%p', '%I:%M %p']

class EditEventForm(forms.ModelForm):
    event_time = forms.TimeField(required=True, widget=time_widget, help_text='ex: 10:30AM', input_formats=valid_time_formats)

views.py relevant code:

...
form = EditEventForm(request.POST or None, instance = instance)
...

Update I want to allow the user to enter times like 10:00 or 10:00AM. So I need all these formats: '%H:%M', '%I:%M%p', '%I:%M %p'

It would be nice if the text in the form field showed the time with the time a day (eg 10:00AM), but the seconds removed would also suffice (eg 10:00).

您能以您的形式做:

event_time = forms.TimeField(widget=forms.TimeInput(format='%H:%M'))

I just added js until I find a better solution:

      var event_time = $('#id_event_time').val();
      if (event_time.length > 5) {
        var new_event_time = event_time.slice(0,-3)
        $('#id_event_time').val(new_event_time);
      }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM