Django 2.0完整性错误非NULL约束失败

时间:2018-07-31 18:48:02

标签: python django database sqlite web-deployment

我正在尝试显示笔记的内容,这些内容已通过NotesCreateForm从登录用户接受。窗体显示正确,但是当我单击提交时,而不是显示DetailView,它给出了以下错误。我是Django的新手,请帮助!还请提出CBV是否合适的建议,还是应该更改为FBV?

Views.py

class NotesCreateView(LoginRequiredMixin,CreateView):
    model=Notes
    form_class=NotesCreateForm
    redirect_field_name='notes_detail.html' 

class NotesListView(ListView):
    model=Notes

class NotesDetailView(LoginRequiredMixin,DetailView):
    model=Notes

Models.py

class Notes(models.Model):
    user=models.ForeignKey(User,on_delete=models.CASCADE)
    title=models.CharField(max_length=255)
    subject=models.CharField(max_length=255)
    text=models.TextField()

    def get_absolute_url(self):
        return reverse('notes_detail',kwargs={'pk':self.pk})

Forms.py

class NotesCreateForm(forms.ModelForm):
    class Meta:
        model=Notes
        fields=('title','subject','text')

Urls.py

from django.contrib import admin
from django.urls import path
from django.conf.urls import url
from EnoteApp import views
from django.contrib.auth import views as auth_views

urlpatterns = [
    path('admin/', admin.site.urls),
    url(r'^login/$', auth_views.login, name='login'),
    url(r'^logout/$', auth_views.logout, name='logout'),
    url(r'^signup/$',views.signup,name='signup'),
    url(r'^$',views.HomeView.as_view(),name='home'),
    url(r'^about/$',views.AboutView.as_view(),name='about'),
    url(r'^notes/list/$',views.NotesListView.as_view(),name='notes_list'),
    url(r'^notes/create/$',views.NotesCreateView.as_view(),name='notes_create'),
    url(r'^notes/(?P<pk>\d+)/$',views.NotesDetailView.as_view(),name='notes_detail'),   
]

错误

Internal Server Error: /notes/create/
Traceback (most recent call last):
  File "C:\Users\Chan\Anaconda3\envs\myDjangoEnv\lib\site-packages\django\db\backends\utils.py", line 85, in _execute
    return self.cursor.execute(sql, params)
  File "C:\Users\Chan\Anaconda3\envs\myDjangoEnv\lib\site-packages\django\db\backends\sqlite3\base.py", line 303, in execute
    return Database.Cursor.execute(self, query, params)
sqlite3.IntegrityError: NOT NULL constraint failed: EnoteApp_notes.user_id

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

Traceback (most recent call last):
  File "C:\Users\Chan\Anaconda3\envs\myDjangoEnv\lib\site-packages\django\core\handlers\exception.py", line 35, in inner
    response = get_response(request)
  File "C:\Users\Chan\Anaconda3\envs\myDjangoEnv\lib\site-packages\django\core\handlers\base.py", line 128, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\Chan\Anaconda3\envs\myDjangoEnv\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\Chan\Anaconda3\envs\myDjangoEnv\lib\site-packages\django\views\generic\base.py", line 69, in view
    return self.dispatch(request, *args, **kwargs)
  File "C:\Users\Chan\Anaconda3\envs\myDjangoEnv\lib\site-packages\django\contrib\auth\mixins.py", line 52, in dispatch
    return super().dispatch(request, *args, **kwargs)
  File "C:\Users\Chan\Anaconda3\envs\myDjangoEnv\lib\site-packages\django\views\generic\base.py", line 89, in dispatch
    return handler(request, *args, **kwargs)
  File "C:\Users\Chan\Anaconda3\envs\myDjangoEnv\lib\site-packages\django\views\generic\edit.py", line 172, in post
    return super().post(request, *args, **kwargs)
  File "C:\Users\Chan\Anaconda3\envs\myDjangoEnv\lib\site-packages\django\views\generic\edit.py", line 142, in post
    return self.form_valid(form)
  File "C:\Users\Chan\Anaconda3\envs\myDjangoEnv\lib\site-packages\django\views\generic\edit.py", line 125, in form_valid
    self.object = form.save()
  File "C:\Users\Chan\Anaconda3\envs\myDjangoEnv\lib\site-packages\django\forms\models.py", line 456, in save
    self.instance.save()
  File "C:\Users\Chan\Anaconda3\envs\myDjangoEnv\lib\site-packages\django\db\models\base.py", line 729, in save
    force_update=force_update, update_fields=update_fields)
  File "C:\Users\Chan\Anaconda3\envs\myDjangoEnv\lib\site-packages\django\db\models\base.py", line 759, in save_base
    updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
  File "C:\Users\Chan\Anaconda3\envs\myDjangoEnv\lib\site-packages\django\db\models\base.py", line 842, in _save_table
    result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
  File "C:\Users\Chan\Anaconda3\envs\myDjangoEnv\lib\site-packages\django\db\models\base.py", line 880, in _do_insert
    using=using, raw=raw)
  File "C:\Users\Chan\Anaconda3\envs\myDjangoEnv\lib\site-packages\django\db\models\manager.py", line 82, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "C:\Users\Chan\Anaconda3\envs\myDjangoEnv\lib\site-packages\django\db\models\query.py", line 1125, in _insert
    return query.get_compiler(using=using).execute_sql(return_id)
  File "C:\Users\Chan\Anaconda3\envs\myDjangoEnv\lib\site-packages\django\db\models\sql\compiler.py", line 1281, in execute_sql
    cursor.execute(sql, params)
  File "C:\Users\Chan\Anaconda3\envs\myDjangoEnv\lib\site-packages\django\db\backends\utils.py", line 100, in execute
    return super().execute(sql, params)
  File "C:\Users\Chan\Anaconda3\envs\myDjangoEnv\lib\site-packages\django\db\backends\utils.py", line 68, in execute
    return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
  File "C:\Users\Chan\Anaconda3\envs\myDjangoEnv\lib\site-packages\django\db\backends\utils.py", line 77, in _execute_with_wrappers
    return executor(sql, params, many, context)
  File "C:\Users\Chan\Anaconda3\envs\myDjangoEnv\lib\site-packages\django\db\backends\utils.py", line 85, in _execute
    return self.cursor.execute(sql, params)
  File "C:\Users\Chan\Anaconda3\envs\myDjangoEnv\lib\site-packages\django\db\utils.py", line 89, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "C:\Users\Chan\Anaconda3\envs\myDjangoEnv\lib\site-packages\django\db\backends\utils.py", line 85, in _execute
    return self.cursor.execute(sql, params)
  File "C:\Users\Chan\Anaconda3\envs\myDjangoEnv\lib\site-packages\django\db\backends\sqlite3\base.py", line 303, in execute
    return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: NOT NULL constraint failed: EnoteApp_notes.user_id

2 个答案:

答案 0 :(得分:1)

您可能在user字段未传递任何值时填写表格。将此添加到您的视图:

class NotesCreateView(LoginRequiredMixin,CreateView):
    model=Notes
    form_class=NotesCreateForm
    redirect_field_name='notes_detail.html'

    def form_valid(self, form):
        form.instance.user = self.request.user
        return super(NotesCreateView, self).form_valid(form)

这会将注释分配给当前登录的用户。

答案 1 :(得分:0)

在NotesCreateView中,您必须指定连接DetailView的success_url。

按如下所示更改NotesCreateView

class NotesCreateView(LoginRequiredMixin,CreateView):
   model=Notes
   form_class=NotesCreateForm
   def get_success_url(self, *args, **kwargs):
       return reverse('notes_detail',kwargs={'pk':self.object.pk}

我希望这对您有用。