You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django表单提交后due_date字段无法保存的问题求助

问题:提交表单后due_date字段无法保存至数据库

提交表单/POST请求后,due_date输入值无法保存到数据库,控制台无报错信息,其余字段均可正常保存。相关代码如下:

Model代码

from datetime import date
from django.db import models
from django.contrib.auth.models import User

class Todo(models.Model):
    title = models.CharField(max_length=100)
    memo = models.TextField(blank=True)
    created = models.DateTimeField(auto_now_add=True)
    due_date = models.DateField(null=True, blank=True)
    datecompleted = models.DateTimeField(null=True, blank=True)
    important = models.BooleanField(default=False)
    user = models.ForeignKey(User, on_delete=models.CASCADE)

    def __str__(self):
        return self.title

Form代码

from django import forms
from .models import Todo

class TodoForm(forms.ModelForm):
    class Meta:
        model = Todo
        fields = ['title', 'memo', 'due_date', 'important']
        due_date = forms.DateField(
        widget=forms.DateInput(format='%m/%d/%Y'),
        input_formats=('%m/%d/%Y', )
        )

View代码

@login_required
def createtodo(request):
    if request.method == 'GET':
        return render(request, 'todo/createtodo.html', {'form':TodoForm()})
    else:
        try:
            form = TodoForm(request.POST)
            newtodo = form.save(commit=False)
            newtodo.user = request.user
            newtodo.save()
            
            return redirect('currenttodos')
        except ValueError:
            return render(request, 'todo/createtodo.html', {'form':TodoForm(), 'error':'Bad data passed in. Try again.'})

HTML表单代码

<form method="POST">
                {% csrf_token %}
                <div class="form-group">
                    <label for="title">Title</label>
                    <input type="text" name="title" class="form-control" id="title" required>
                </div>
                <div class="form-group">
                    <label for="due_date">Due</label>
                    <input type="date" class="form-control" id="due_date" value="{{todo.due_date}}">
                </div>
                <div class="form-group">
                    <label for="memo">Memo</label>
                    <textarea name="memo" class="form-control" id="memo" ></textarea>
                </div>
                <div class="form-group form-check">
                    <input type="checkbox" name="important" class="form-check-input" id="important">
                    <label class="form-check-label" for="important">Important</label>
                </div>
                <button type="submit" class="btn btn-primary">Save</button>
            </form>

解决方法

1. 补全HTML表单中due_date输入框的name属性

HTML里的due_date输入框缺失name="due_date"属性,导致表单提交时不会将该字段值发送到后端。修改后的代码:

<div class="form-group">
    <label for="due_date">Due</label>
    <input type="date" name="due_date" class="form-control" id="due_date" value="{{todo.due_date}}">
</div>

2. 修正Form类中due_date字段的定义位置

在ModelForm中,自定义字段需要定义在Meta类外部,否则配置不会生效。修改后的代码:

from django import forms
from .models import Todo

class TodoForm(forms.ModelForm):
    due_date = forms.DateField(
        widget=forms.DateInput(format='%m/%d/%Y'),
        input_formats=('%m/%d/%Y', )
    )
    
    class Meta:
        model = Todo
        fields = ['title', 'memo', 'due_date', 'important']

额外提示

浏览器原生type="date"输入框默认以YYYY-MM-DD格式提交数据,若要保留自定义的%m/%d/%Y格式,需确保前端输入与后端input_formats匹配,或直接使用Django表单渲染(如{{ form.due_date }})自动处理格式问题,避免手动编写HTML输入框引发的格式不兼容。

内容的提问来源于stack exchange,提问作者HB21

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 09:27:41