Django models.DateTimeField django.db.utils.IntegrityError:NOT NULL约束失败

时间:2017-09-12 02:01:29

标签: python django sqlite

有什么问题?我用谷歌搜索,没有发现任何接近我所拥有的东西。保存配置文件然后继续到下一页会产生错误。

我正在使用sqlite开发服务器。

谢谢。

models.py

class SchoolProfile(models.Model):
    create_date = models.DateTimeField(
        null=False, blank=False, **auto_now_add=True,**
        verbose_name=u'Fecha de creación')
    modification_date = models.DateTimeField(
        null=False, blank=False, **auto_now=True,**
        verbose_name=u'Fecha de última modificación')
    cycle = models.CharField(
        null=False, blank=False, max_length=9,
        verbose_name='Ciclo escolar')
    name = models.CharField(
        null=False, blank=False, max_length=100,
        verbose_name='Nombre de la escuela')

    def __unicode__(self):
        return '{} {}'.format(self.cycle, self.name)

    class Meta:
        db_table = 'Perfil Escolar'
        ordering = ['id', 'name']
        verbose_name = 'Perfil Escolar'
        verbose_name_plural = 'Perfiles Escolares'

    class Admin:
        pass


class SchoolServices(models.Model):

    school_profile = models.ForeignKey(
        SchoolProfile,
        on_delete=models.CASCADE)
    tipo = models.IntegerField(
        choices=SCHOOL_TYPE_CHOICES, default=SCHOOL_TYPE_KINDER,
        verbose_name='Tipo de Escuela')
    folio = models.CharField(
        null=True, blank=True, max_length=40,
        verbose_name='Folio')

    def __unicode__(self):
        return '{} [{}]'.format(self.tipo, self.folio)

    class Meta:
        db_table = 'Servicio Escolar'
        ordering = ['tipo', 'folio']
        verbose_name = 'Servicio Escolar'
        verbose_name_plural = 'Servicios Escolares'

    class Admin:
        pass

forms.py

class SchoolProfileForm(ModelForm):
    class Meta:
        model = SchoolProfile
        readonly_fields = (
            'create_date',
            'modification_date',)
        fields = (
            'cycle',
            'name',)


class SchoolServicesForm(ModelForm):
    class Meta:
        model = SchoolServices
        fields = (
            'tipo',
            'folio',)

views.py

class SchoolProfileView(LoginRequiredMixin, CreateView):
    model = SchoolProfile
    form_class = SchoolProfileForm
    context_object_name = 'school'
    template_name = 'profile/school_profile.html'

    def get_success_url(self, **kwargs):
        return reverse(
            'profile_edit',
            kwargs={'pk': self.object.id})

urls.py

urlpatterns = [
    url(r'^create$',
        views.SchoolProfileView.as_view(),
        name='profile_create'), ]

使用'Admin'界面我可以填写创建表单,但在我提交'save'后,我收到以下错误:

Internal Server Error: /admin/profile/schoolprofile/add/
Traceback (most recent call last):
  File "/Users/francisco.benavides/.pyenv/versions/django311/lib/python3.4/site-packages/django/db/backends/utils.py", line 65, in execute
return self.cursor.execute(sql, params)
  File "/Users/francisco.benavides/.pyenv/versions/django311/lib/python3.4/site-packages/django/db/backends/sqlite3/base.py", line 328, in execute
return Database.Cursor.execute(self, query, params)
sqlite3.IntegrityError: NOT NULL constraint failed: Perfil 
Escolar.create_date

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/Users/francisco.benavides/.pyenv/versions/django311/lib/python3.4/site-packages/django/core/handlers/exception.py", line 41, in inner
response = get_response(request)
  File "/Users/francisco.benavides/.pyenv/versions/django311/lib/python3.4/site-packages/django/core/handlers/base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/Users/francisco.benavides/.pyenv/versions/django311/lib/python3.4/site-packages/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Users/francisco.benavides/.pyenv/versions/django311/lib/python3.4/site-packages/django/contrib/admin/options.py", line 551, in wrapper
return self.admin_site.admin_view(view)(*args, **kwargs)
  File "/Users/francisco.benavides/.pyenv/versions/django311/lib/python3.4/site-packages/django/utils/decorators.py", line 149, in _wrapped_view
response = view_func(request, *args, **kwargs)
  File "/Users/francisco.benavides/.pyenv/versions/django311/lib/python3.4/site-packages/django/views/decorators/cache.py", line 57, in _wrapped_view_func
response = view_func(request, *args, **kwargs)
  File "/Users/francisco.benavides/.pyenv/versions/django311/lib/python3.4/site-packages/django/contrib/admin/sites.py", line 224, in inner
return view(request, *args, **kwargs)
  File "/Users/francisco.benavides/.pyenv/versions/django311/lib/python3.4/site-packages/django/contrib/admin/options.py", line 1508, in add_view
return self.changeform_view(request, None, form_url, extra_context)
  File "/Users/francisco.benavides/.pyenv/versions/django311/lib/python3.4/site-packages/django/utils/decorators.py", line 67, in _wrapper
return bound_func(*args, **kwargs)
  File "/Users/francisco.benavides/.pyenv/versions/django311/lib/python3.4/site-packages/django/utils/decorators.py", line 149, in _wrapped_view
response = view_func(request, *args, **kwargs)
  File "/Users/francisco.benavides/.pyenv/versions/django311/lib/python3.4/site-packages/django/utils/decorators.py", line 63, in bound_func
return func.__get__(self, type(self))(*args2, **kwargs2)
  File "/Users/francisco.benavides/.pyenv/versions/django311/lib/python3.4/site-packages/django/contrib/admin/options.py", line 1408, in changeform_view
return self._changeform_view(request, object_id, form_url, extra_context)
  File "/Users/francisco.benavides/.pyenv/versions/django311/lib/python3.4/site-packages/django/contrib/admin/options.py", line 1448, in _changeform_view
self.save_model(request, new_object, form, not add)
  File "/Users/francisco.benavides/.pyenv/versions/django311/lib/python3.4/site-packages/django/contrib/admin/options.py", line 979, in save_model
obj.save()
  File "/Users/francisco.benavides/.pyenv/versions/django311/lib/python3.4/site-packages/django/db/models/base.py", line 807, in save
force_update=force_update, update_fields=update_fields)
  File "/Users/francisco.benavides/.pyenv/versions/django311/lib/python3.4/site-packages/django/db/models/base.py", line 837, in save_base
updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
  File "/Users/francisco.benavides/.pyenv/versions/django311/lib/python3.4/site-packages/django/db/models/base.py", line 923, in _save_table
result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
  File "/Users/francisco.benavides/.pyenv/versions/django311/lib/python3.4/site-packages/django/db/models/base.py", line 962, in _do_insert
using=using, raw=raw)
  File "/Users/francisco.benavides/.pyenv/versions/django311/lib/python3.4/site-packages/django/db/models/manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/Users/francisco.benavides/.pyenv/versions/django311/lib/python3.4/site-packages/django/db/models/query.py", line 1076, in _insert
return query.get_compiler(using=using).execute_sql(return_id)
  File "/Users/francisco.benavides/.pyenv/versions/django311/lib/python3.4/site-packages/django/db/models/sql/compiler.py", line 1107, in execute_sql
cursor.execute(sql, params)
  File "/Users/francisco.benavides/.pyenv/versions/django311/lib/python3.4/site-packages/django/db/backends/utils.py", line 80, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
  File "/Users/francisco.benavides/.pyenv/versions/django311/lib/python3.4/site-packages/django/db/backends/utils.py", line 65, in execute
return self.cursor.execute(sql, params)
  File "/Users/francisco.benavides/.pyenv/versions/django311/lib/python3.4/site-packages/django/db/utils.py", line 94, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
  File "/Users/francisco.benavides/.pyenv/versions/django311/lib/python3.4/site-packages/django/utils/six.py", line 685, in reraise
raise value.with_traceback(tb)
  File "/Users/francisco.benavides/.pyenv/versions/django311/lib/python3.4/site-packages/django/db/backends/utils.py", line 65, in execute
return self.cursor.execute(sql, params)
  File "/Users/francisco.benavides/.pyenv/versions/django311/lib/python3.4/site-packages/django/db/backends/sqlite3/base.py", line 328, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: NOT NULL constraint failed: Perfil Escolar.create_date

2 个答案:

答案 0 :(得分:0)

看来你的日期时间提交(create_date)不为空,我认为不会分配日期归档值,有两个处理此错误

  

如果需要日期时间字段,您可以这样做

class SchoolProfile(models.Model):
        create_date = models.DateTimeField(
                   null=False, blank=False,
                   verbose_name=u'Fecha de creación',auto_now_add=True)

我在插入新记录时在create_date字段中添加了额外的关键字,其当前日期时间为当地时区

  

如果不需要提交日期时间

class SchoolProfile(models.Model):
        create_date = models.DateTimeField(
                   null=True, blank=True,
                   verbose_name=u'Fecha de creación')

答案 1 :(得分:0)

发生错误是因为您没有给NOT NULL字段赋值。在您的情况下,NOT NULL字段是'created_date'和'modification_date'

您可以使用auto_now-add = True使其仅在创建对象时自动获取该字段的当前系统时间。因此,您可以将其用于created_date,因为它只会在创建对象时更新。

对于modification_date,需要在对对象进行的所有修改时更新。为此,可以使用'auto_now = True'。

看起来像这样:

MySQL [chuangwai]> SELECT TABLE_COLLATION
    -> FROM INFORMATION_SCHEMA.TABLES
    -> WHERE TABLE_NAME = 'items';
+-----------------+
| TABLE_COLLATION |
+-----------------+
| utf8_unicode_ci |
+-----------------+