Django admin selection field dynamically populated with universal foreign key fields

Let's say I have the following simple models for some tagging applications (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 *, I understand from the documentation that I need to pass two field names in accordance with the contenttype structure. In my case, the content_type field is specified in the template model. I would like to avoid duplicating the content_type field in the "tag" model in order to get the GenericForeignKey working. Is it possible? Or do I need some kind of user manager to implement a duplicate content_type in the tag?

2) . content_type_field, content_type (.. TagTemplate) Tabularinline?

. - ( content_type) tagTemplate, ( "name", "age", "dob" ). , TabularInline "content_type_field" , . tagTemplate content_type, tagTemplateItemDisplay content_type_field inline .

+3
1

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**

TagAdmin :

form = TagTemplateForm

, .

, .

+1

Source: https://habr.com/ru/post/1718032/


All Articles