python - Django 错误:“您正在尝试在没有默认值的情况下将不可为空的字段‘作者’添加到条目中”
问题描述
在我的models.py文件中添加作者字段后,我试图进行迁移,但Django问我这个:
You are trying to add a non-nullable field 'author' to entry without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:
1) Provide a one-off default now (will be set on all existing rows with a null value for this column)
2) Quit, and let me add a default in models.py
我的 Models.py 文件:
from django.db import models
from django.utils import timezone
from django.urls import reverse
from django.contrib.auth.models import User
class Entry(models.Model):
title = models.CharField(max_length=50, default=timezone.now)
date = models.DateTimeField(default=timezone.now)
content = models.TextField()
author = models.ForeignKey(User, on_delete=models.CASCADE)
def get_absolute_url(self):
return reverse('diary:index')
def __str__(self):
return self.title
我想将当前处于活动状态的用户添加为作者,因此我在 views.py 文件中执行了此操作:
class EntryCreate(CreateView):
model = Entry
fields = ['title', 'content']
def form_valid(self, form):
form.instance.author = self.request.author
return super().form_valid(form)
我应该怎么做才能避免这种情况?
提前致谢!
解决方案
添加default=None
到您的作者
推荐阅读
- azure - 如何创建 Azure 管道以在虚拟机中提取 github 存储库
- microsoft-teams - MS Teams - 检测弹出窗口已打开
- swift - 如何在 SwiftUI 中绘制圆的径向切片?(即饼状图)
- node.js - 如何自动化 NodeJS/npm 依赖更新?
- sharepoint - 为什么站点权限中缺少 Sharepoint 站点所有者组?
- amazon-web-services - 使用 Terraform 管理访问 RDS 数据库的凭据时出现问题
- sql-server - 从 2014 年升级到 SQL Server 2017 后受信任的程序集功能中断
- java - 按位表示为字节数组函数
- java - 在 springdoc 中禁用 JSR-303 注释处理
- c# - 如何从 UI c# 与正在运行的任务进行通信