首页 > 解决方案 > 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')

标签: djangodjango-models

解决方案


推荐阅读