django - Django model : save object with custom field
问题描述
I would like to know how I can do that : save an object in my database through Django model with custom field.
This is my modelclass :
class Document(EdqmTable):
language = models.CharField(max_length=2, verbose_name=_('language'), choices=LANGUAGE_CHOICES, null=False)
format = models.CharField(max_length=10, verbose_name=_('format'), choices=FORMAT_CHOICES, null=False)
title = models.CharField(max_length=512, verbose_name=_('document title'), null=False)
publication = models.ForeignKey(Publication, verbose_name=_('publication title'), null=False,
related_name='documents')
class Meta:
verbose_name = _('document')
verbose_name_plural = _('documents')
def save(self, *args, **kwargs):
self.title = f"{self.publication.pub_id}-{self.format.upper()}"
super(Document, self).save(*args, **kwargs)
I have a save
method, which let to define my field title
with combination between two fields.
title
field is hidden in my django form and is set automatically by Django.
But, up to now, it doesn't work because my object is not saved into my database. Something is wrong in my save
function ?
EDIT :
I edited my post with forms.py file and my view :
The field document.title
is used in my django forms with formset like this :
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', 'pub_id', 'category']
class DocumentForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(DocumentForm, self).__init__(*args, **kwargs)
self.fields['title'].widget = forms.HiddenInput()
for key in self.fields:
self.fields[key].required = True
class Meta:
model = Document
fields = ['publication', 'language', 'format', 'title', 'upload']
DocumentFormSet = inlineformset_factory(Publication, Document, form=DocumentForm, extra=1)
And my view according to this part :
class PublicationCreateView(EdqmCreateView):
""" Create publication with document form through formset """
model = Publication
template_name = 'freepub/publication_form.html'
def get_context_data(self, **kwargs):
context = super(PublicationCreateView, self).get_context_data(**kwargs)
context['document_form'] = DocumentFormSet(self.request.POST or None, self.request.FILES or None)
return context
def form_valid(self, form):
context = self.get_context_data()
document = context['document_form']
if document.is_valid():
self.object = form.save()
document.instance = self.object
document.save()
return super(PublicationCreateView, self).form_valid(form)
def get_success_url(self):
return reverse('publication-list-crud')
解决方案
推荐阅读
- javascript - 尝试从 Blazor 服务器应用程序调用 js
- python-3.x - 如何返回具有相等数量的 0 和 1 值的所有行?
- html - HTML 背景颜色和字体未在 Chrome 或 Firefox 中显示
- java - 模仿默认 Maven Failsafe 配置的简单现代 Gradle 配置
- amazon-web-services - Lambda function in isolated VPC subnet can't access SSM parameter
- css - .entry-content ul li 随机截断单词(仅限手机)
- python - 对多类问题执行 K 折交叉验证,评分 = 'f1 or Recall or Precision'
- r - 如何从 ggplot 获取(未设置)轴最小值和最大值?
- r - 使用 keep、discard 和 filter 将数据帧保留在数据帧列表中
- angular - CombineLatest 导致多个流提交