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

Django注册表单添加first_name和last_name时触发NOT NULL约束IntegrityError报错

报错原因

这个错误是因为你创建Subscriber实例时传入的first_name值为None,但数据库中members_subscriber表的first_name字段设置了非空约束,不允许存空值。

排查步骤

  • 第一步:检查表单类的字段配置
    你当前的SubscriberSignUpForm的Meta类只指定了关联模型,没有显式声明要包含first_name和last_name字段,表单默认不会处理这两个字段的提交和清洗,导致cleaned_data中这两个字段的值为None。
  • 第二步:检查前端模板
    确认注册页面的表单中已经正确渲染了first_name、last_name两个输入框,输入框的name属性必须和字段名完全一致,否则提交的数据不会被表单接收。
  • 第三步:检查模型字段配置
    查看Subscriber模型的first_name、last_name字段是否设置了null=True,如果业务中这两个字段允许为空,可以配置该参数跳过非空校验。
  • 第四步:检查代码语法问题
    你贴出的Subscriber.objects.create方法中,first_name和last_name的赋值语句末尾多了多余的逗号,可能导致赋值异常。

解决方案

  1. 修正表单类的Meta配置,显式添加需要处理的字段:
class SubscriberSignUpForm(UserCreationForm):
    class Meta(UserCreationForm.Meta):
        model = UserManagement
        # 追加需要处理的字段,表单会自动对这些字段做必填校验
        fields = UserCreationForm.Meta.fields + ('email', 'first_name', 'last_name')

    @transaction.atomic
    def save(self):
        user = super().save(commit=False)
        user.is_subscriber = True
        user.save()
        Subscriber.objects.create(
            user=user,
            email=self.cleaned_data.get('email'),
            # 去掉末尾多余的逗号
            first_name = self.cleaned_data.get('first_name'),
            last_name = self.cleaned_data.get('last_name')
        )
        my_group = Group.objects.get(name='subscriber')
        if user.is_subscriber == True:
            my_group.user_set.add(user) 
        return user
  1. 如果业务允许这两个字段为空,修改Subscriber模型对应字段配置后执行迁移:
# models.py中修改字段
class Subscriber(models.Model):
    # 其他字段不变
    first_name = models.CharField(max_length=50, null=True, blank=True)
    last_name = models.CharField(max_length=50, null=True, blank=True)

修改后执行python manage.py makemigrations和python manage.py migrate更新数据库表结构。
3. 确认前端模板中已经添加两个字段的输入框,示例:

<form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">注册</button>
</form>

如果是手动写输入框,确保name属性正确:

<input type="text" name="first_name" required>
<input type="text" name="last_name" required>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 03:21:03