Friday, July 9, 2021

get_changeform_initial_data with ManyToMany


Hello,

How can I use admin's get_changeform_initial_data function to prepopulate a many to many relationship widget ?

I have the following models in models.py :
___________________________________________________
class Piece(models.Model):
    vehicules = models.ManyToManyField(Vehicule, through='AppartenanceVehicule', verbose_name='véhicules')
    soustypes_piece = models.ManyToManyField(SousTypePiece, blank=False, default=None, verbose_name='sous-types de pièce')

class AppartenanceVehicule(models.Model):
    vehicule = models.ForeignKey(Vehicule, on_delete=models.CASCADE)
    piece = models.ForeignKey(Piece, on_delete=models.CASCADE)
    annee = models.PositiveSmallIntegerField('année', blank=True, null=True, validators=[MinValueValidator(1900), MaxValueValidator(2100)])

class SousTypePiece(models.Model):
    # some attributes

class Vehicule(models.Model):
   # some attributes
___________________________________________________

I use the following function in admin.py's ModelAdmin for Piece model :

_______________________________
def get_changeform_initial_data(self, request):
   if request.GET.get('vehicule_pk') and request.GET.get('soustype_piece_pk'):
        vehicule = get_object_or_404(Vehicule, pk=request.GET.get('vehicule_pk'))
        soustype_piece = get_object_or_404(SousTypePiece, pk=request.GET.get('soustype_piece_pk'))
       return {
          'vehicules': vehicule,
          'soustypes_piece': soustype_piece
       }
   elif request.GET.get('vehicule_pk'):
       vehicule = get_object_or_404(Vehicule, pk=request.GET.get('vehicule_pk'))
       return {
          'vehicules': vehicule,
       }
__________________________________

but I can only prepopulate soustypes_piece correctly. I remember I could prepopulate vehicules when I didn't use an intermediate model (using 'through'). This may be why I can still prepopulate soustypes_piece.

Any idea how I can make it work ?

Thanks,

Thibault

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/f952109d-07bb-4662-87f4-7bcdad275de6n%40googlegroups.com.

No comments:

Post a Comment