5

I faced with the same issue as described here or here.

In short: I have 2 models: Book and Shelf. In admin form ("add shelf") I would like to select from the books that are already in the library. By default this is not available.

I used the solution (from links above) and everything works until I try to "save" new object .

Error:

Unsaved model instance (Shelf: ShelfAlpha) cannot be used in an ORM query.

#models.py
class Book(models.Model):
    shelf = models.ForeignKey(Shelf, blank=True, null=True,
        related_name="in_shelf")

#admin.py
class ShelfForm(forms.ModelForm):
    class Meta:
        model = Shelf

    books = forms.ModelMultipleChoiceField(queryset=Book.objects.all())

    def __init__(self, *args, **kwargs):
        super(ShelfForm, self).__init__(*args, **kwargs)
        if self.instance:
            if self.instance.in_shelf:
                self.fields['books'].initial = self.instance.in_shelf.all()
            else:
                self.fields['books'].initial = []

    def save(self, *args, **kwargs):    
        instance = super(ShelfForm, self).save(commit=False)
        self.fields['books'].initial.update(shelf=None)
        self.cleaned_data['books'].update(shelf=instance)
        return instance

It seems like in 2014 was working but now it's not.

I would appreciate for help!

Ralf
  • 16,086
  • 4
  • 44
  • 68

0 Answers0