How to generate a 'limit_choices' with the 'id' of a table previously selected in '/ admin'

1

I am using 'GenericForeigKey' to relate several models to only one, I have the following code:

class IPuertoOptico(models.Model):
    nomenclatura = models.CharField(max_length=30)

    limit = models.Q(app_label='infrastructure', model='itarjeta') |  \
        models.Q(app_label='infrastructure', model='iequipo')

    content_type = models.ForeignKey(
        ContentType,
        limit_choices_to=limit,
        on_delete=models.CASCADE)

    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')

    autor = models.ForeignKey(settings.AUTH_USER_MODEL)
    fecha_hora_alta = models.DateTimeField(
    null=True, blank=True, default=timezone.now)

    class Meta:
        verbose_name_plural = "Puertos Opticos "

    def __str__(self):
            return '%s' % (self.nomenclatura)

In Admin.py I have the following:

class IPuertoOpticoAdmin(admin.ModelAdmin):

    list_display = [f.name for f in IPuertoOptico._meta.fields]
    exclude = ('autor', 'fecha_hora_alta',)

    def save_model(self, request, obj, form, change):
        obj.autor = request.user
        obj.save()
admin.site.register(IPuertoOptico, IPuertoOpticoAdmin)

The problem is that in the '/ admin' to put a value in object_id I have to be consulting the 'id' in the previously selected object in 'content_type'

What I want to do is put a 'limit_choices_to' in the field 'object_id' that is auto filled with the id of the previously selected object in the field 'content_type'.

Can someone help me please.

    
asked by Rocke 01.09.2016 в 14:43
source

1 answer

0

If you can change the subject of the admin and you can use Django Grapelli, it may work for you. Django Grapelli allows you to use 'autocomplete_lookup_fields' in the admin. You can see an example here:

link

Personally I edited the admin form of my model and created a javascript code that captured the selected model (contentype) and then asked for the list of objects to a web service (a view that returns a JSON). This JSON object was loaded in a SELECT and when the user selects a particular object, an event wrote the id to the object_id field.

In summary, there is no immediate configuration that allows you to do this.

    
answered by 05.09.2016 / 01:30
source