Django写入数据库,IntegrityError

标签 django postgresql ubuntu model django-south

我的网页的注册 View (如下)通过 Django 的身份验证模型 User 创建了一个新用户,然后使用该新创建的用户 ID 通过我自己的模型 account.Users 添加更多信息。我的问题是,虽然我将新用户的 ID 传递给第二个模型(account.Users 中的 ForeignKey 列),但我一直收到一个错误,即列 *user_id* 违反了非空约束:

IntegrityError at /account/signup/ 
null value in column "user_id" violates not-null constraint

以下是我的模型的相关部分:
class Users(models.Model):
  user = models.ForeignKey(User, unique=True, null=True, blank=True)
  firstname = models.CharField(max_length=100, blank=True, default='')

以及我观点的相关部分:
def signup(request):
  if request.method == 'POST' and request.POST['firstname']:   
    user = User.objects.create_user(request.POST['username'], request.POST['email'], request.POST['password'])
    userId = user.id
    form = UsersForm(request.POST, request.FILES)
    if form.is_valid():
      cmodel = form.save()
      cmodel.user_id = userId
      cmodel.firstname = request.POST['firstname']
      cmodel.save()

此错误的原因可能是什么?

除了将 *cmodel.user_id* 设置为等于 userId 之外,我还尝试将其设置为等于在第一步中创建的用户对象,以及字符串和 int(分别为“1”和 1)。我每次都得到同样的错误。我也尝试将字段更改为 cmodel.user。我还可以从 Django 的错误页面中看出变量 userId 实际上包含一个值。

最佳答案

解决方案很简单,尽管出乎意料。我把它写在这里以防其他人遇到同样的问题:

除了上面展示的模型的总结部分,我还尝试使用 PIL (Python Imaging Library) 保存图像。 .将其添加到上面显示的模型的相关部分:

class Users(models.Model):
  user = models.ForeignKey(User, unique=True, null=True, blank=True)
  firstname = models.CharField(max_length=100, blank=True, default='')
  profile_pic = models.ImageField(upload_to='profilepics', max_length=300, default='')

这个“upload_to”文件夹“profilepics”具有访问权限“755”,但是当我通过在终端中运行“$ chmod -R 777 profilepics”更改它们时,一切正常!奇怪的是,错误消息将其归咎于我的“user_id”字段为空。这实际上只是完全不同的东西的文件夹权限。希望有一天能对某人有所帮助。

关于Django写入数据库,IntegrityError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17868762/

相关文章:

android-studio - 具有高密度显示的 Android Studio 上的微小字体

php - 允许 WebRoot-Directory 访问上层目录

Django Rest框架在条件后禁用字段更新

Python 复杂查询

json - 需要使用 Curl 上传 JSON 和图像文件

django - Ajax - 如何自动保存我的 Django 表单

json - 在 postgres 中将记录作为 json 数组加入

java - 加载 Postgresql JDBC 4.1 驱动程序

sql - 选择记录并将其作为函数参数传递

php - MySQL 无法使用 PHP 建立连接