What are the steps to make a ModelForm work with a ManyToMany relationship with an intermediary model in Django?

前端 未结 5 1459
借酒劲吻你
借酒劲吻你 2020-12-23 11:46
  • I have a Client and Groupe Model.
  • A Client can be part of multiple groups.
  • Clients that are part of a gr
5条回答
  •  情书的邮戳
    2020-12-23 12:17

    I'm providing an alternative solution due to issues I encountered with forms_valid not being called:

    class SplingCreate(forms.ModelForm):
    class Meta:
        model = SplingModel
        fields = ('Link', 'Genres', 'Image', 'ImageURL',)
    
    def save(self, commit=True):
        from django.forms.models import save_instance
    
        if self.instance.pk is None:
            fail_message = 'created'
        else:
            fail_message = 'changed'
        fields = set(self._meta.fields) - set(('Genres',))
        instance = save_instance(self, self.instance, fields,
                                 fail_message, commit, construct=False)
    
        genres = self.cleaned_data.get('Genres')
        for genre in genres:
            SplingGenreModel.objects.get_or_create(spling=instance, genre=genre)
    
        return instance
    

    I've copied the logic from djangos forms/models.py, my field Genres is a manytomany with an intermediary table - I exclude it from the save_instance and then save it separately.

提交回复
热议问题