--这是我在StackOverflow上的第一个问题。因此,如果我违反了任何社区规则/标准,我道歉。尽管周围也有类似的问题,但没有答案帮助我解决我遇到的问题。我想说我不是一个足够好的程序员来找出解决方案---
当我点击publish添加一个新帖子时,我得到以下错误
“django.db.utils.IntegrityError:”“用户id”“列中的值为空”
违反非空约束详细信息:失败的行包含(18,s,s,
2019-05-26 15:39:10.466636+00,无效。“
我试过传球。。。。
ForeignKey('auth.User')
还有。。。
ForeignKey(get_user_model()
在后模型(不知道它怎么可能有助于我的问题。
我将数据库从sqlite迁移到PostgreSQL,然后检查PgAdmin上的Post表,查看用户id(以前命名为author_id)是否存在。
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.urls import reverse
from django.contrib.auth import get_user_model
User = get_user_model()
class Post(models.Model):
user = models.ForeignKey(User, related_name='posts', on_delete=models.CASCADE)
title = models.CharField(max_length=200)
text = models.TextField()
published_date = models.DateTimeField(auto_now=True)
def __str__(self):
"""String representation"""
return self.title
def get_absolute_url(self):
"""Returns the url to access a detailed post"""
return reverse('post-detail', kwargs={"pk": self.pk})
class Meta:
ordering = ['-published_date']
unique_together = ('user',)
视图文件:
class CreatePostView(CreateView):
model = Post
template_name = 'blog/addpost.html'
fields = ('title', 'text')
这是回溯:
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/blog/addpost
Django Version: 2.2.1
Python Version: 3.7.2
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blog',
'django.contrib.humanize']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback:
File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\db\backends\utils.py" in _execute
84. return self.cursor.execute(sql, params)
The above exception (null value in column "user_id" violates not-null constraint
DETAIL: Failing row contains (18, s, s, 2019-05-26 15:39:10.466636+00, null).
) was the direct cause of the following exception:
File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\core\handlers\exception.py" in inner
34. response = get_response(request)
File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\core\handlers\base.py" in _get_response
115. response = self.process_exception_by_middleware(e, request)
File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\core\handlers\base.py" in _get_response
113. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\views\generic\base.py" in view
71. return self.dispatch(request, *args, **kwargs)
File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\views\generic\base.py" in dispatch
97. return handler(request, *args, **kwargs)
File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\views\generic\edit.py" in post
172. return super().post(request, *args, **kwargs)
File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\views\generic\edit.py" in post
142. return self.form_valid(form)
File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\views\generic\edit.py" in form_valid
125. self.object = form.save()
File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\forms\models.py" in save
458. self.instance.save()
File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\db\models\base.py" in save
741. force_update=force_update, update_fields=update_fields)
File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\db\models\base.py" in save_base
779. force_update, using, update_fields,
File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\db\models\base.py" in _save_table
870. result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\db\models\base.py" in _do_insert
908. using=using, raw=raw)
File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\db\models\manager.py" in manager_method
82. return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\db\models\query.py" in _insert
1186. return query.get_compiler(using=using).execute_sql(return_id)
File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\db\models\sql\compiler.py" in execute_sql
1335. cursor.execute(sql, params)
File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\db\backends\utils.py" in execute
99. return super().execute(sql, params)
File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\db\backends\utils.py" in execute
67. return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\db\backends\utils.py" in _execute_with_wrappers
76. return executor(sql, params, many, context)
File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\db\backends\utils.py" in _execute
84. return self.cursor.execute(sql, params)
File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\db\utils.py" in __exit__
89. raise dj_exc_value.with_traceback(traceback) from exc_value
File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\db\backends\utils.py" in _execute
84. return self.cursor.execute(sql, params)
Exception Type: IntegrityError at /blog/addpost
Exception Value: null value in column "user_id" violates not-null constraint
DETAIL: Failing row contains (18, s, s, 2019-05-26 15:39:10.466636+00, null).
我创建了使用Django的迷你博客来实践基于类的视图,并对代码和Django环境有了更多的了解。我遵循了非常相似的步骤,但没有遇到这样的错误。
编辑:
这是addpost.html
{% extends "base.html" %}
{% block content %}
<form action="{% url 'add-post' %}" method="POST">
{% csrf_token %}
<ul>
<p>{{request.user}}</p>is adding a post:
<li>
<label for="title">Post Title</label>
<input type="text" name="title" value="" required>
<label for="text">Post text</label>
<input type="text" name="text" value="">
<button type="submit" name="button">Publish</button>
<a href="{% url 'blog-view' %}">
<button type="submit" name="button">Cancel & Go Back</button>
</a>
</li>
</ul>
</form>
{% endblock %}