简体   繁体   中英

Django admin choice field dynamically populated by generic foreign key's model fields

Say I have the following simple models for some tagging application (this is simplified from the actual code):

# Model of tag templates
class TagTemplate(models.Model):
    name = models.CharField()
    content_type = models.ForeignKey(ContentType)

class Tag(models.Model):
    template = models.ForeignKey(TagTemplate)
    object_id = models.PositiveIntegerField()
 *  content_object = generic.GenericForeignKey('template__content_type', 'object_id') 

# Each tag may display the 
class TagTemplateItemDisplay(models.Model):
    template = models.ForeignKey(TagTemplate)
    content_type_field = models.CharField()
    font_size = models.IntegerField()

I have two questions:

1) In the line marked with the *, I understand from the documentation that I need to pass the two field names as per the contenttype framework. In my case the content_type field is specified within the template model. I'd like to avoind a duplicate content_type field within the 'tag' model to get the GenericForeignKey working. Is this possible? Or do I need some custom manager to implement a duplicate content_type within the tag model?

2) I'd like to use the admin site with these models. Is it possible to dynamically create a choice dropdown for the 'content_type_field' field where the contents corresponds to a list of fields from the chosen content_type of the parent model (ie. tagTemplate) when using Tabularinline layout?

eg. in the admin site I pick a model (content_type field) for a new tagTemplate record that contains the fields ('name', 'age', 'dob'), I'd like the TabularInline forms to dynamically update the 'content_type_field' to contain the choices name, age and dob. If i then pick a different model in the parent tagTemplate content_type field, the choices in the child tagTemplateItemDisplay content_type_field of the inline are updated again.

You can subclass the form for that model

class TagTemplateForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(TagTemplateForm, self).__init__(*args, **kwargs)
        if self.instance.content_type == SomeContentType:
            **dynamically create your fields here**
        elif self.instance.content_type == SomeOtherContentType:
            **dynamically create your other fields here**

Then in your TagAdmin model you need to have:

form = TagTemplateForm

to override the default form created for the admin site.

Not a complete solution but should get you started.

For the dynamic form generation, you might start by reading over this

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM