Django 完整性错误不为空

Django Integrity Error Not null

我正在学习 Django 并尝试通过制作我自己的网站来练习,该网站将对我提交的问题进行测验。我收到此错误,我不知道为什么。

IntegrityError at /questions/new/ NOT NULL constraint failed: questions_question.date_created

这是我认为的相关回溯

Environment:


Request Method: POST
Request URL: http://127.0.0.1:8000/questions/new/

Django Version: 1.11
Python Version: 3.5.0
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'bootstrap3',
 'accounts',
 'posts',
 'groups',
 'questions']
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 "/Users/chrismaltez/anaconda3/envs/SimpleSocialEnv/lib/python3.5/site-packages/django/db/backends/utils.py" in execute
  65.                 return self.cursor.execute(sql, params)

File "/Users/chrismaltez/anaconda3/envs/SimpleSocialEnv/lib/python3.5/site-packages/django/db/backends/sqlite3/base.py" in execute
  328.         return Database.Cursor.execute(self, query, params)

The above exception (NOT NULL constraint failed: questions_question.date_created) was the direct cause of the following exception:

File "/Users/chrismaltez/anaconda3/envs/SimpleSocialEnv/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner
  41.             response = get_response(request)

File "/Users/chrismaltez/anaconda3/envs/SimpleSocialEnv/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "/Users/chrismaltez/anaconda3/envs/SimpleSocialEnv/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/Users/chrismaltez/anaconda3/envs/SimpleSocialEnv/lib/python3.5/site-packages/django/views/generic/base.py" in view
  68.             return self.dispatch(request, *args, **kwargs)

File "/Users/chrismaltez/anaconda3/envs/SimpleSocialEnv/lib/python3.5/site-packages/django/views/generic/base.py" in dispatch
  88.         return handler(request, *args, **kwargs)

File "/Users/chrismaltez/anaconda3/envs/SimpleSocialEnv/lib/python3.5/site-packages/django/views/generic/edit.py" in post
  217.         return super(BaseCreateView, self).post(request, *args, **kwargs)

File "/Users/chrismaltez/anaconda3/envs/SimpleSocialEnv/lib/python3.5/site-packages/django/views/generic/edit.py" in post
  183.             return self.form_valid(form)

File "/Users/chrismaltez/Desktop/pycharmprojects/UDEMY/test/questions/views.py" in form_valid
  31.         self.object.save()

File "/Users/chrismaltez/Desktop/pycharmprojects/UDEMY/test/questions/models.py" in save
  33.         super().save(*args, **kwargs)

File "/Users/chrismaltez/anaconda3/envs/SimpleSocialEnv/lib/python3.5/site-packages/django/db/models/base.py" in save
  806.                        force_update=force_update, update_fields=update_fields)

File "/Users/chrismaltez/anaconda3/envs/SimpleSocialEnv/lib/python3.5/site-packages/django/db/models/base.py" in save_base
  836.             updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)

File "/Users/chrismaltez/anaconda3/envs/SimpleSocialEnv/lib/python3.5/site-packages/django/db/models/base.py" in _save_table
  922.             result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)

File "/Users/chrismaltez/anaconda3/envs/SimpleSocialEnv/lib/python3.5/site-packages/django/db/models/base.py" in _do_insert
  961.                                using=using, raw=raw)

File "/Users/chrismaltez/anaconda3/envs/SimpleSocialEnv/lib/python3.5/site-packages/django/db/models/manager.py" in manager_method
  85.                 return getattr(self.get_queryset(), name)(*args, **kwargs)

File "/Users/chrismaltez/anaconda3/envs/SimpleSocialEnv/lib/python3.5/site-packages/django/db/models/query.py" in _insert
  1060.         return query.get_compiler(using=using).execute_sql(return_id)

File "/Users/chrismaltez/anaconda3/envs/SimpleSocialEnv/lib/python3.5/site-packages/django/db/models/sql/compiler.py" in execute_sql
  1099.                 cursor.execute(sql, params)

File "/Users/chrismaltez/anaconda3/envs/SimpleSocialEnv/lib/python3.5/site-packages/django/db/backends/utils.py" in execute
  80.             return super(CursorDebugWrapper, self).execute(sql, params)

File "/Users/chrismaltez/anaconda3/envs/SimpleSocialEnv/lib/python3.5/site-packages/django/db/backends/utils.py" in execute
  65.                 return self.cursor.execute(sql, params)

File "/Users/chrismaltez/anaconda3/envs/SimpleSocialEnv/lib/python3.5/site-packages/django/db/utils.py" in __exit__
  94.                 six.reraise(dj_exc_type, dj_exc_value, traceback)

File "/Users/chrismaltez/anaconda3/envs/SimpleSocialEnv/lib/python3.5/site-packages/django/utils/six.py" in reraise
  685.             raise value.with_traceback(tb)

File "/Users/chrismaltez/anaconda3/envs/SimpleSocialEnv/lib/python3.5/site-packages/django/db/backends/utils.py" in execute
  65.                 return self.cursor.execute(sql, params)

File "/Users/chrismaltez/anaconda3/envs/SimpleSocialEnv/lib/python3.5/site-packages/django/db/backends/sqlite3/base.py" in execute
  328.         return Database.Cursor.execute(self, query, params)

Exception Type: IntegrityError at /questions/new/
Exception Value: NOT NULL constraint failed: questions_question.date_created

ScreenShot of the error

这是我的相关代码:

questions/Views.py

from django.shortcuts import render
from django.views import generic
from django.core.urlresolvers import reverse_lazy
from django.contrib import messages

from . import models
from . import forms


# Create your views here.

class QuestionList(generic.ListView):
    model = models.Question


class QuestionDetail(generic.DetailView):
    model = models.Question

    def get_queryset(self):
        queryset = super().get_queryset()


class CreateQuestion(generic.CreateView):
    model = models.Question
    # form = QuestionForm
    fields = ('question', 'answer')

    def form_valid(self, form):
        self.object = form.save(commit=False)
        self.object.user = self.request.user
        self.object.save()
        return super().form_valid(form)


class DeleteQuestion(generic.DeleteView):
    model = models.Question
    success_url = reverse_lazy('questions:all')

    def get_queryset(self):
        queryset = super().get_queryset()
        return queryset.filter(user_id=self.request.user.id)

    def delete(self, *args, **kwargs):
        messages.success(self.request, "Question Deleted")
        return super().delete(*args, **kwargs)

这是我的 models.py

from django.db import models
from django.contrib.auth import get_user_model
from django.core.urlresolvers import reverse
User = get_user_model()

import misaka

# Create your models here.
class Quiz(models.Model):
    name = models.CharField(max_length=225)
    intro_text = models.TextField(null=True)
    date_created = models.DateTimeField()
    date_updated = models.DateTimeField(auto_now=True, null=True)


class Question(models.Model):
    user = models.ForeignKey(User, related_name="question", default='')
    quiz = models.ForeignKey(Quiz)
    question = models.TextField(unique=False, default='')
    question_html = models.TextField(default='')
    date_created = models.DateTimeField()
    date_updated = models.DateTimeField(auto_now=True, null=True)
    answer = models.TextField(default='')
    answer_html = models.TextField(unique=False, default='')
    # message = models.TextField(unique=False, default='')
    # message_html = models.TextField(editable=False, default='')

    def __str__(self):
        return self.question

    def save(self, *args, **kwargs):
        self.question_html = misaka.html(self.question)
        super().save(*args, **kwargs)

    def get_absolute_url(self):
        return reverse(
            "questions:single",
            kwargs={
                "username": self.user.username,
                "pk": self.pk
            }
        )

    class Meta:
        # ordering = ["-created_at"]
        unique_together = ["user", "question", "answer", ]



class QuestionAnswer(models.Model):
    question = models.ForeignKey(Question)
    answer = models.TextField(unique=False)
    answer_html = models.TextField()
    correct = models.BooleanField(default=False)
    date_created = models.DateTimeField()
    date_updated = models.DateTimeField(auto_now=True, null=True)

如有任何帮助,我们将不胜感激!

当您在问题模型中创建一个新问题时,只提到了两个字段。除了 date_created 所有剩余字段将为空或默认值。所以列 date_create 在模型中也像这样改变:

date_created = models.DateTimeField(auto_now=True, null=True)

因为如果你没有提到 null = True 约束默认是 Not Null。这就是为什么当您尝试添加它时显示完整性错误。