Python 版本: 3.7 姜戈版本 2.1.1
我是 django 的新手,我主要是在教程和"试错"的帮助下自学。我已经搜索了堆栈溢出,但之前的问题似乎都不适合我的问题。例如,他们指的是空白的CharFields,我认为这不是我的问题。
我想,我通过外键将神学院和论文这两个班级联系起来。 现在,我可以通过适当的表格将神学院添加到数据库中,并以我想要的方式显示它。 但是考虑到类论文的第二种形式,django 给了我错误:
请求方法:开机自检
异常类型:完整性错误
异常值:非空约束失败:papers_paper.seminary_id
论文是我的应用程序,顺便说一句
这是 models.py,没有元:
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视图中 现在它给了我以下错误。
异常类型:配置不正确
异常值:没有要重定向到的 URL。 提供网址或 在模型上定义get_absolute_url方法。
无论如何,不应该有研讨会的选择:每份论文只分配给一个特定的研讨会。
完成回溯,在更改视图PaperCreate后:
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.py:
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)])
如文档中建议的那样。
现在我的模板有问题,但我会为此设置一个新问题。 到目前为止非常感谢!
我也不是专家,但我认为这是因为您的 PaperCreate 视图无法像数据库预期的那样将 Paper 对象链接到神学院对象。每个 Paper 对象都应具有神学院对象的 ID,因为您已在 Paper 模型类中添加了该 ID:
class Paper(models.Model):
seminary = models.ForeignKey(Seminary, on_delete=models.CASCADE, primary_key=True)
并且由于外键字段不能为空,因此会引发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)
IntegrityError, NOT NULL 约束失败: papers_paper.seminary_id.
此错误意味着您在 Paper 模型中具有非 null 约束的 Seminary 的外键,但在创建 Paper 对象时,您没有传递 Seminary(外键(的值。