Django 2.1.1,IntegrityError,NOT NULL约束失败:papers_paper.seminary_id

问题描述 投票:0回答:2

Python版本:3.7 Django版本2.1.1

我是django的新手,我主要是在教程和“试错”的帮助下自学。我搜索了stackoverflow,但以前的问题似乎都不适合我的问题。例如,它们指的是空白的CharFields,我认为这不是我的问题。

我想,我通过ForeignKey将两个类的神学院和论文联系起来。现在我可以通过适当的表单将Seminary添加到数据库中,并按照我想要的方式显示它。但考虑到Paper类的第二种形式,django给了我错误:

请求方法:POST

异常类型:IntegrityError

异常值:NOT NULL约束失败:papers_paper.seminary_id

论文是我的应用程序,顺便说一句

这是models.py,没有meta:

class Seminary(models.Model):
slug = models.SlugField(unique=True)
seminary_type = models.CharField(max_length=25, choices=choices.SEMINARY_TYPE_CHOICES)
seminary_title = models.CharField(max_length=200)
seminary_year = models.IntegerField(choices=choices.YEAR_CHOICES, default=datetime.now().year)
summer_winter = models.CharField(max_length=6, choices=choices.SEASON_CHOICES, default="S")

def get_absolute_url(self):
    return reverse('papers:paper-detail', kwargs={'slug': self.slug})

def __str__(self):
    return self.seminary_title


def create_slug(instance, new_slug=None):
    slug = slugify(instance.seminary_title)
    if new_slug is not None:
        slug = new_slug
    qs = Seminary.objects.filter(slug=slug)
    exists = qs.exists()
    if exists:
        new_slug = "%s-%s" % (slug, qs.first().pk)
        return create_slug(instance, new_slug=new_slug)
    return slug


def pre_save_post_receiver(sender, instance, *args, **kwargs):
    if not instance.slug:
        instance.slug = create_slug(instance)


pre_save.connect(pre_save_post_receiver, sender=Seminary)


class Paper(models.Model):
    seminary = models.ForeignKey(Seminary, on_delete=models.CASCADE, primary_key=True)
    paper_title = models.CharField(max_length=200, blank=False, help_text="Please enter the title ")
    author = models.CharField(max_length=50, blank=True)
    upload_paper = ContentTypeRestrictedFileField(
        upload_to='papers/pdf',
        content_types=['application/pdf'],
        max_upload_size=5242880,
        blank=True
    )

    def get_absolute_url(self):
        return reverse('papers:paper-index', kwargs={'slug': self.slug})

这是views.py:

class IndexView(generic.ListView):
    template_name = 'papers/index.html'
    context_object_name = 'all_papers'

    def get_queryset(self):
        return Seminary.objects.all()


class DetailView(generic.DetailView):
    model = Seminary
    template_name = 'papers/detail.html'


class SeminaryCreate(CreateView):
    model = Seminary
    fields = ['summer_winter',
              'seminary_year',
              'seminary_type',
              'seminary_title',
              ]


class PaperCreate(CreateView):
    model = Paper
    fields = [
        'paper_title',
        'author',
        'upload_paper',
    ]

我敢肯定,我正在混淆什么。如果我需要提供更多信息,请询问,我会将其添加到我的问题中。提前致谢!

编辑:

我根据@bluegrounds的建议在PaperCreate视图中添加了神学院现在它给了我以下错误。

异常类型:NotperlyConfigured

异常值:没有要重定向到的URL。在模型上提供url或定义get_absolute_url方法。

无论如何,不​​应该选择研讨会:每篇论文只分配给一个特定的研讨会。

更改视图PaperCreate后完成Traceback:

Request Method: POST
Request URL: http://127.0.0.1:8000/papers/seminartitel15/add/

Django Version: 2.1.1
Python Version: 3.7.0
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'transcript.apps.TranscriptConfig',
 'biblio.apps.BiblioConfig',
 'papers.apps.PapersConfig',
 'crispy_forms']
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 "/usr/lib/python3.7/site-packages/django/views/generic/edit.py" in get_success_url
  116.                 url = self.object.get_absolute_url()

File "/home/bjoern/MyCode/PycharmProjects/websiteTwo/websiteTwo/papers/models.py" in get_absolute_url
  68.         return reverse('papers:paper-index', kwargs={'slug': self.slug})

During handling of the above exception ('Paper' object has no attribute 'slug'), another exception occurred:

File "/usr/lib/python3.7/site-packages/django/core/handlers/exception.py" in inner
  34.             response = get_response(request)

File "/usr/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response
  126.                 response = self.process_exception_by_middleware(e, request)

File "/usr/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response
  124.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/usr/lib/python3.7/site-packages/django/views/generic/base.py" in view
  68.             return self.dispatch(request, *args, **kwargs)

File "/usr/lib/python3.7/site-packages/django/views/generic/base.py" in dispatch
  88.         return handler(request, *args, **kwargs)

File "/usr/lib/python3.7/site-packages/django/views/generic/edit.py" in post
  172.         return super().post(request, *args, **kwargs)

File "/usr/lib/python3.7/site-packages/django/views/generic/edit.py" in post
  142.             return self.form_valid(form)

File "/usr/lib/python3.7/site-packages/django/views/generic/edit.py" in form_valid
  126.         return super().form_valid(form)

File "/usr/lib/python3.7/site-packages/django/views/generic/edit.py" in form_valid
  57.         return HttpResponseRedirect(self.get_success_url())

File "/usr/lib/python3.7/site-packages/django/views/generic/edit.py" in get_success_url
  119.                     "No URL to redirect to.  Either provide a url or define"

Exception Type: ImproperlyConfigured at /papers/seminartitel15/add/
Exception Value: No URL to redirect to.  Either provide a url or define a get_absolute_url method on the Model.

URLs.朋友:

urlpatterns = [
    path('papers/new/', views.SeminaryCreate.as_view(), name='seminary-add'),
    path('papers/', views.IndexView.as_view(), name='paper-index'),
    path('papers/<str:slug>/', views.DetailView.as_view(), name='paper-detail'),
    path('papers/<str:slug>/add/', views.PaperCreate.as_view(), name='paper-add'),

]

Edit_2:我无法解决整个问题,但@bluegrounds的建议很有帮助。另外我改变了班级论文的get_absolute_url

 def get_absolute_url(self):
        return reverse('papers:paper-detail', args=[str(self.seminary.slug)])

正如文档中所建议的那样。

现在我的模板出了问题,但我会为此设置一个新问题。非常感谢到目前为止!

python django null constraints
2个回答
1
投票

我不是专家,但我认为这是因为您的PaperCreate视图没有办法将Paper对象链接到Seminary对象,就像数据库期望的那样。每个Paper对象都应具有Seminary对象的id,因为您已在Paper模型类中添加了该对象:

class Paper(models.Model):
    seminary = models.ForeignKey(Seminary, on_delete=models.CASCADE, primary_key=True)

并且因为ForeignKey字段不能为null,所以它会提高NOT NULL constraint failed: papers_paper.seminary_id

所以也许这样做,看看它是否有效:

class PaperCreate(CreateView):
    model = Paper
    fields = [
        'seminary',
        'paper_title',
        'author',
        'upload_paper',
    ]

如果我没记错的话,CreateView应该在具有可用神学对象的网页上显示下拉菜单。

边注

你确定这里的主键属性吗?

class Paper(models.Model):
    seminary = models.ForeignKey(Seminary, on_delete=models.CASCADE, primary_key=True)

0
投票

IntegrityError,NOT NULL约束失败:papers_paper.seminary_id。 此错误意味着您在Paper模型中具有非空约束的外键,但在创建Paper对象时,您没有传递Seminary(外键)的值。

© www.soinside.com 2019 - 2024. All rights reserved.