如何在 Django 2 模型和模板中使用 DatetimeField

Posted

技术标签:

【中文标题】如何在 Django 2 模型和模板中使用 DatetimeField【英文标题】:How to use DatetimeField in Django 2 models and Templates 【发布时间】:2019-06-13 08:17:07 【问题描述】:

我正在处理一个需要使用几个 DateTime 字段的项目,我在模型中定义了DatetimeField,然后在模板中使用了https://tempusdominus.github.io/bootstrap-4/ 插件,但是当我提交表格有两个问题来了:

1): Django 对所有 DateTime 字段说 Enter a valid date/time 2):选择一个有效的选项。 ['corn_oil'] 不是可用的选项之一。

这是我尝试过的:

来自models.py

choices = (
    ('CO2 SCRUBBER', 'CO2 SCRUBBER'),
    ('corn_oil', 'CORN OIL'),
    ('DRYERS', 'DRYERS'),
    ('ENVIRONMENTAL', 'ENVIRONMENTAL'),
    ('UTILITIES', 'UTILITIES'),
    ('LAB', 'LAB'),
    ('SIEVES', 'SIEVES'),
    ('GRAINS & MILLING', 'GRAINS & MILLING'),
    ('SEPARATION', 'SEPARATION'),
    ('AIR & GAS', 'AIR & GAS'),
    ('COOK', 'COOK'),
    ('EVAPORATION', 'EVAPORATION'),
    ('WATER', 'WATER'),
    ('STORAGE', 'STORAGE'),
    ('BOILER', 'BOILER'),
    ('FERMENTATION', 'FERMENTATION'),
    ('DISTILLATION', 'DISTILLATION'),
    ('BUILDING AND FACILITIES', 'BUILDING AND FACILITIES'),
    ('CHEMICAL', 'CHEMICAL'),
)


class ExperimentModel(models.Model):
    user = models.ForeignKey(User, related_name='experiments',
                             on_delete=models.CASCADE)
    name = models.CharField(max_length=255)
    start_date = models.DateTimeField()
    change_date = models.DateTimeField()
    end_date = models.DateTimeField()
    assets = models.CharField(max_length=450, choices=choices)
    goals = models.CharField(max_length=255, blank=True)
    comments = models.TextField(max_length=1000)
    created_at = models.DateTimeField(auto_now=True)

来自forms.py

class ExperimentForm(forms.ModelForm):
    choices = (
        ('CO2 SCRUBBER', 'CO2 SCRUBBER'),
        ('corn_oil', 'CORN OIL'),
        ('DRYERS', 'DRYERS'),
        ('ENVIRONMENTAL', 'ENVIRONMENTAL'),
        ('UTILITIES', 'UTILITIES'),
        ('LAB', 'LAB'),
        ('SIEVES', 'SIEVES'),
        ('GRAINS & MILLING', 'GRAINS & MILLING'),
        ('SEPARATION', 'SEPARATION'),
        ('AIR & GAS', 'AIR & GAS'),
        ('COOK', 'COOK'),
        ('EVAPORATION', 'EVAPORATION'),
        ('WATER', 'WATER'),
        ('STORAGE', 'STORAGE'),
        ('BOILER', 'BOILER'),
        ('FERMENTATION', 'FERMENTATION'),
        ('DISTILLATION', 'DISTILLATION'),
        ('BUILDING AND FACILITIES', 'BUILDING AND FACILITIES'),
        ('CHEMICAL', 'CHEMICAL'),
    )
    assets = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple,
                                       choices=choices)
    # assets = ModelMultipleChoiceField(queryset=Thing.objects.all(), widget=Select2MultipleWidget)

    class Meta:
        model = ExperimentModel
        fields = ('user', 'name', 'start_date', 'change_date', 'end_date', 'assets',
                  'goals', 'comments')

来自views.py def post(self, request, *args, **kwargs): post_data = request.POST.copy() post_data.update('user': request.user.pk) 表格 = ExperimentForm(post_data) 如果 request.method == 'POST': print('请求提交') 如果 form.is_valid(): print('表格有效') form.save(提交=假) form.user = request.user form.save() return HttpResponseRedirect('所有实验') return render_to_response('experiment/new_experiment.html', 'form': form)

以及我如何在模板中显示 DateTime 字段和选择字段: 来自new-experiment.html

<div class="form-group">
                <input type="text" name="name" id="name" class="form-control input-lg"
                       placeholder="experiment name" tabindex="3" required>
            </div>
            <div class="form-group">
                <label for="datetimepicker1"> Start Date </label>
                <div class="input-group date" id="datetimepicker1" data-target-input="nearest">
                    <input type="text" name="start_date" class="form-control datetimepicker-input"
                           data-target="#datetimepicker1"/>
                    <div class="input-group-append" data-target="#datetimepicker1" data-toggle="datetimepicker">
                        <div class="input-group-text"><i class="fa fa-calendar"></i></div>
                    </div>
                </div>
            </div>
            <div class="form-group">
                <label for="datetimepicker2"> Change Date </label>
                <div class="input-group date" id="datetimepicker2" data-target-input="nearest">
                    <input type="text" name="change_date" class="form-control datetimepicker-input"
                           data-target="#datetimepicker2"/>
                    <div class="input-group-append" data-target="#datetimepicker2" data-toggle="datetimepicker">
                        <div class="input-group-text"><i class="fa fa-calendar"></i></div>
                    </div>
                </div>
            </div>
            <div class="form-group">
                <label for="datetimepicker3"> End Date </label>
                <div class="input-group date" id="datetimepicker3" data-target-input="nearest">
                    <input type="text" name="end_date" class="form-control datetimepicker-input"
                           data-target="#datetimepicker3" placeholder="dd/mm/yy"/>
                    <div class="input-group-append" data-target="#datetimepicker3" data-toggle="datetimepicker">
                        <div class="input-group-text"><i class="fa fa-calendar"></i></div>
                    </div>
                </div>
            </div>

            <script type="text/javascript">
                $(function () 
                    $('#datetimepicker1').datetimepicker();
                    $('#datetimepicker2').datetimepicker();
                    $('#datetimepicker3').datetimepicker();
                );
            </script>
            <div class="form-group">
                <label for="assets"> Assets </label>
                                <input type="text" name="assets" id="assets" class="form-control input-lg"
                                       placeholder="Assets" tabindex="3" required>
                <select name="assets" class="form-control select_field_class" id="assets">
                    <option value="CO2 SCRUBBER">CO2 SCRUBBER</option>
                    <option value="corn_oil">CORN OIL</option>
                    <option value="DRYERS">DRYERS</option>
                    <option value="ENVIRONMENTAL">ENVIRONMENTAL</option>
                    <option value="UTILITIES">UTILITIES</option>
                    <option value="LAB">LAB</option>
                    <option value="SIEVES">SIEVES</option>
                    <option value="GRAINS & MILLING">GRAINS & MILLING</option>
                    <option value="SEPARATION">SEPARATION</option>
                    <option value="AIR & GAS">AIR & GAS</option>
                    <option value="COOK">COOK</option>
                    <option value="EVAPORATION">EVAPORATION</option>
                    <option value="WATER">WATER</option>
                    <option value="STORAGE">STORAGE</option>
                    <option value="BOILER">BOILER</option>
                    <option value="FERMENTATION">FERMENTATION</option>
                    <option value="BUILDING AND FACILITIES">BUILDING AND FACILITIES</option>
                    <option value="CHEMICAL">CHEMICAL</option>
                </select>
            </div>
            <div class="form-group">
                <label for="assets"> Goals </label>
                <input type="text" name="goals" id="goals" class="form-control input-lg"
                       placeholder="Goals" tabindex="3" required>
            </div>
            <div class="form-group">
                <label for="comments"> Comments </label>
                <textarea name="comments" id="comments" class="form-control input-lg"
                          rows="5" required>
                    </textarea>
            </div>

我也想对资产使用多选,但尚未实现。

请给我掌舵!

提前致谢!

【问题讨论】:

【参考方案1】:
import datetime

class ExperimentModel(models.Model):
    start_date = models.DateTimeField(auto_now_add=True, blank=True)
    change_date = models.DateTimeField(blank=True)
    end_date = models.DateTimeField(blank=True)

【讨论】:

请补充说明。

以上是关于如何在 Django 2 模型和模板中使用 DatetimeField的主要内容,如果未能解决你的问题,请参考以下文章

如何通过Django中的模板函数与现有数据库和模型交互

我们可以格式化模型表单如何在模板上的 Django 中显示吗

我们可以格式化模型表单如何在模板上的 Django 中显示吗

Django:如何在 ajax 中返回模型表单集并在模板中使用

如何在模型 TextField 的 HTML 中使用 Django 模板变量?

Django:如何在新模板中的另一个模型上使用 CreateView 的 form_valid() 返回的响应?