不节省UTC时间

时间:2019-03-11 22:51:00

标签: python django forms time

我有一个带有TimeField的表单,该表单从动态创建的下拉列表中获取输入。我所有其他表格都根据用户时区成功地转换了日期和时间,并将它们保存为UTC格式在数据库中。我在此特定表格上输入的时间似乎没有发生这种情况。我相信这是因为它从我拥有的列表中获取字符串值,但是我不确定如何更改它,因为该列表是动态生成的输入列表的记录方式所必需的。如果能找到一种方法来动态生成我的时间下拉菜单并将其保存在UTC中,我将不胜感激。

HTML

<div class="form-group">
    <label>Time</label>
    {{ form.booked_time }}
</div>

models.py

class Booked(models.Model):
    booked_time = models.TimeField(null=True, blank=True)

forms.py

class BookedForm(forms.ModelForm):
    booked_time = forms.ChoiceField(choices=time_list, widget=forms.Select(attrs={'class' : 'form-control', 'id' : 'time', 'required' : 'True'}))
 'booked_time')

带有类似这样的time_list

('', 'Time'),
('8:00 am', '8:00 am'),
('8:15 am', '8:15 am'),
('8:30 am', '8:30 am'),

views.py

def book_lesson(request, lesson_id):
    if request.user.is_authenticated and request.user.time_zone:
        activate(request.user.time_zone)
    else:
        deactivate()

    lesson = Lesson.objects.get(id=lesson_id)

    if request.method == 'POST':
        form = BookedForm(request.POST)

        if form.is_valid():
            book = form.save(commit=False)
            book.student_user = request.user
            book.teacher_user = lesson.user
            book.save()
            messages.success(request,'Lesson was successfully booked!')
            return redirect('/teacher/dashboard')

        else:
            form = BookedForm()

    form = BookedForm()
    context = {'form' : form, 'lesson' : lesson}
    return render(request, 'view/book_lesson.html', context)

JavaScript

var start = document.getElementById('start').innerHTML.split('.').join('').toLocaleLowerCase();
var end = document.getElementById('end').innerHTML.split('.').join('').toLocaleLowerCase();
var time = document.getElementById('time');

time.disabled = true;

var slotTimes = [];
document.getElementById("length").onchange = function (evt) {
    var timeDistance = evt.target.value;
    var startMoment = moment(start, "h:mm a");
    var endMoment = moment(end, "h:mm a");
    slotTimes = [];

    while (startMoment.isSameOrBefore(endMoment)) {
        slotTimes.push(startMoment.format("h:mm a"));
        startMoment = startMoment.add(timeDistance, 'minutes');
    }

    addDropdown();
    disabled();
};
function addDropdown() {
    var doc = '',
        times = slotTimes,
        i;
    for (i = 0; i < times.length; i++) {
        doc += "<option value='" + times[i] + "'>" + times[i] + "</option>";
    }

    document.getElementById('time').innerHTML = doc;
    disabled();
}

0 个答案:

没有答案