Django日期时间格式:参数必须为字符串错误

rqcrx0a6  于 2022-12-14  发布在  Go
关注(0)|答案(3)|浏览(183)

我尝试将日期信息保存到数据库,但遇到类型错误:

def message_send(request):
    if request.user.is_authenticated:
        if request.method == 'POST':
            name = request.user.username
            email = request.user.get_email
            title = request.POST.get('title')
            message = request.POST.get('message')
            date = models.DateTimeField(default=timezone.now)
            support = supportmessages(name=name,email=email,title=title,message=message,date=date)
            support.save()
            messages.success(request, 'Your mesaage has been sent')
            return render(request,"messagesend.html")
        return render(request,"messagesend.html")
    else:
        return redirect(request,"{% url 'home' %}")

代码在这个views.py文件中,我尝试timezone.now,但它不工作。

jhdbpxl9

jhdbpxl91#

用这一行:

date = models.DateTimeField(default=timezone.now)

您实际上是在为date字段提供用于定义数据库字段的django.db.models.DateTimeField类。
应将其替换为要插入的值:

date = timezone.now()
djmepvbi

djmepvbi2#

对不起我的代码在这里

def message_send(request):
if request.user.is_authenticated:
    if request.method == 'POST':
        name = request.user.username
        email = request.user.get_email
        title = request.POST.get('title')
        message = request.POST.get('message')
        date = models.DateTimeField(default=timezone.now)
        support = supportmessages(name=name,email=email,title=title,message=message,date=date)
        support.save()
        messages.success(request, 'Your mesaage has been sent')
        return render(request,"messagesend.html")
    return render(request,"messagesend.html")
else:
    return redirect(request,"{% url 'home' %}")
brc7rcf0

brc7rcf03#

你没有给出日期时间值,所以它会出错。首先从django utils导入时区

from django.utils import timezone

并且更换了

date = models.DateTimeField(default=timezone.now)

date = timezone.now()

相关问题