我正在与Django CBV合作,我第一次尝试使用表单集。我想同时填写两个表单,并将外键作为两者之间的公共元素。
我有两种型号:
class Publication(models.Model):
title = models.CharField(max_length=512, verbose_name=_('title'), null=False, unique=True)
description = models.TextField(verbose_name=_('description'), null=True)
download_limit = models.IntegerField(verbose_name=_('download limit'), null=True)
time_limit = models.IntegerField(verbose_name=_('expiration delay'), null=True)
category = models.ForeignKey(Category, verbose_name=_('category'), null=False)
nb_document = models.IntegerField(verbose_name=_('number of document'), default=0)
creation_date = models.DateTimeField(auto_now_add=True, verbose_name=_('creation date'), null=False)
modification_date = models.DateTimeField(auto_now=True, verbose_name=_('modification date'), null=False)
class Meta:
verbose_name = _('publication')
verbose_name_plural = _('publication')
def __str__(self):
return f"{self.title}"
class Document(models.Model):
FORMAT_CHOICES = (
('pdf', 'pdf'),
('epub', 'epub'),
)
age_id = models.CharField(max_length=12, verbose_name=_('publication ID'), unique=True, default='')
language = models.CharField(max_length=2, verbose_name=_('language'), null=False)
format = models.CharField(max_length=10, verbose_name=_('format'), choices=FORMAT_CHOICES, null=False)
title = models.CharField(max_length=512, verbose_name=_('title'), null=False)
publication = models.ForeignKey(Publication, verbose_name=_('publication'), null=False, related_name='documents')
upload = models.FileField(upload_to='media/', validators=[validate_file_extension])
creation_date = models.DateTimeField(auto_now_add=True, verbose_name=_('creation date'), null=False)
modification_date = models.DateTimeField(auto_now=True, verbose_name=_('modification date'), null=False)
class Meta:
verbose_name = _('document')
verbose_name_plural = _('document')
def __str__(self):
return f"{self.age_id} : {self.title} - {self.publication}"
我在我的表单python文件中定义了表单集:
class PublicationForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['category'].empty_label = _('Select a category') # Modify initial empty_label
class Meta:
model = Publication
fields = ['title', 'category']
class DocumentForm(forms.ModelForm):
class Meta:
model = Document
fields = ['publication', 'age_id', 'language', 'format', 'title', 'upload']
DocumentFormSet = inlineformset_factory(Publication, Document, form=DocumentForm, extra=1)
最重要的是,我的视图是在cruds.py文件中定义的,如下所示:
class PublicationCreateView(AgeCreateView):
model = Publication
template_name = 'app/publication_form.html'
def get_context_data(self, **kwargs):
context = super(PublicationCreateView, self).get_context_data(**kwargs)
if self.request.POST :
context['document_form'] = DocumentFormSet(self.request.POST, self.request.FILES)
else:
context['document_form'] = DocumentFormSet()
return context
def form_valid(self, form):
context = self.get_context_data()
document = context['document_form']
if document.is_valid():
document.instance = self.object
document.save()
return super(PublicationCreateView, self).form_valid(form)
def get_success_url(self):
return reverse('publication-list-crud')
class PublicationCRUDView(MainConfigCRUDManager):
""" CRUD views for Publication """
model = Publication
default_sort_params = ('category', 'asc')
templates = {'create': 'app/publication_form.html'}
custom_views = {'create': PublicationCreateView}
#queryset = Publication.objects.annotate(nb_documents=Count('documents'))
# Configuration of fields
search_fields = ['category', 'title']
list_fields = ['category', 'title', 'creation_date', 'modification_date', 'nb_document']
update_fields = ['category', 'title']
class DocumentCRUDView(MainConfigCRUDManager):
""" CRUD views for Document """
model = Document
default_sort_params = ('title', 'asc')
templates = {'create': 'app/publication_form.html'}
custom_views = {'create': PublicationCreateView}
# Configuration of fields
search_fields = ['age_id', 'title', 'language', 'publication_id.title', 'format']
list_fields = ['age_id', 'title', 'publication', 'language', 'format']
update_fields = ['publication', 'age_id', 'title', 'language', 'format', 'upload']
该模板显示良好,具有通用的表单集,但当我想提交这个组合的表单时,我得到了这个问题:
异常值:“NoneType”对象没有属性“id”
这是回溯:
追踪:
文件“/首页/.pyenv/versions/Publication3.6.2/lib/python3.6/站点包/django/核心/处理程序/异常.py”在内部 41 中。响应 = get_response(请求)
文件“/首页/.pyenv/versions/Publication3.6.2/lib/python3.6/site-packages/django/core/处理程序/base.py”,_get_response 187。响应 = self.process_exception_by_middleware(e, 请求)
_get_response 185中的文件“/home/.pyenv/versions/Publication3.6.2/lib/python3.6/site-packages/django/core/handlers/base.py”。响应=wrapped_callback(请求,*callback_args,**callback_kwargs)
文件"/home/. pyenv/version/Publication3.6.2/lib/python3.6/site-包/django/view/通用/base.py"在视图68.返回self.dispatch(请求,*参数,**kwargs)
在调度 56 中将文件“/主页/.pyenv/versions/Publication3.6.2/lib/python3.6/site-packages/django/contribs/auth/mixins.py”。返回超级(登录要求Mixin,自我).dispatch(请求,*args, **kwargs)
dispatch 116.return super中的文件“/home/.pyenv/versions/Publication3.6.2/lib/python3.6/site-packages/django/contrib/auth/mixins.py”(UserPassesTestMixin,self)。分派(请求,*args,**kwargs)
文件"/home/。pyenv/versions/publication 3 . 6 . 2/lib/python 3.6/site-packages/django/views/generic/base . py "。返回处理程序(请求,*参数,*kwargs)
post 217.return super(BaseCreateView,self)中的文件“/home/.pyenv/versions/Publication3.6.2/lib/python3.6/site-packages/django/views/generic/edit.py”。post(请求,*args,**kwargs)
post 183中的文件“/home/.pyenv/versions/Publication3.6.2/lib/python3.6/site-packages/django/views/generic/edit.py”return self.form_valid(form)
form_valid 49中的文件“/home/Bureau/Projets/Publication/Publication/src/web/app/cruds . py”。document.save()
文件/home/. pyenv/version/Publication3.6.2/lib/python3.6/site-pack/django/form/models.py保存666.返回self.save_existing_objects(提交)self.save_new_objects(提交)
文件"/home/。pyenv/versions/publication 3 . 6 . 2/lib/python 3.6/site-packages/django/forms/models . py”。self . new _ objects . append(self . save _ new(form,commit=commit))
文件"/home/。pyenv/versions/publication 3 . 6 . 2/lib/python 3.6/site-packages/django/forms/models . py”。pk_value = getattr(self.instance,self . fk . remote _ field . field _ name)
异常类型:/crud/publication/create/Exception值处的AttributeError:“NoneType”对象没有属性“id”
我不太清楚id在哪里定义,以及如何解决这个问题。
谢谢你
我找到了答案,但不知道为什么现在行得通,以前行不通。
前面的< code>form_valid()函数:
def form_valid(self, form):
context = self.get_context_data()
document = context['document_form']
if document.is_valid():
document.instance = self.object
document.save()
return super(PublicationCreateView, self).form_valid(form)
这是我的新form_valid()
函数:
def form_valid(self, form):
context = self.get_context_data()
document = context['document_form']
if document.is_valid():
self.object = form.save() #I added this line
document.instance = self.object
document.save()
return super(PublicationCreateView, self).form_valid(form)
如果pk_col值为空,则应打印未定义的主键。但我得到了这个错误。“NoneType”对象没有属性“rdd”。
问题内容: 下面的代码给出了错误: 码: 问题答案: 从代码中,我可以看到你希望允许用户下载pdf。 现在开始 去 http://localhost:5000
问题内容: 我的程序看起来像 当我运行它时,它会抛出我 不知道为什么会这样?当我已经在每个列表的开头创建列表时 问题答案: 实际上,您存储在此处: 更改列表并返回 例:
问题内容: 我遇到了这个问题,我不明白为什么。 我从我的应用程序中获取了代码,并制作了此测试代码,因此您不必费劲地查看我的要求。 我有这个工作在其他代码。但是,在将两者进行比较之后,我无法为自己的一生解决这个问题。 在此应用程序中,出现错误“ AttributeError:’NoneType’对象没有属性’delete’”。 问题答案: 在这一行: grid不返回任何内容,因此entryBox是,
我的模型在Slagify系列中有问题 我试着把代码self.slug=slugify(“slug的测试”)放进去,但问题仍然存在,但当他说保留信息时,没有问题 这是我的错误: 环境: 请求方式:POST请求URL:http://xxx.xx.xx.xx:8000/admin/pages/pages/add/ Django版本:1.7.1 Python版本:3.4.2安装的应用程序:('Django
我遵循项目中给出的所有指示 代码是main.py