SoFunction
Updated on 2024-10-28

django admin to achieve dynamic multiple choice box form sample code

contexts

With django-admin, you can quickly get a CRUD interface, but if you need to create multi-selected labeled fields, you need to make adjustments to the form

typical example

  • A tag (label class), a book (book class)
  • book carries the tag, here without resorting to foreign keys that have performance issues
class tag():
    name = (max_length=20, verbose_name='Tags')
 
 
class book():
    name = (max_length=50, verbose_name='Title of the book')
    tags = (null=True, verbose_name='Tags')

 

Register the corresponding mod to admin in order to be found and used by django-admin, so the main steps are here, with the following notes:

  • values_list returns: <QuerySet [('tag1', 'tag1'), ('tag2', 'tag2')]>
  • Guaranteed up-to-date tag list: perform a tag lookup only once at form initialization
  • Form modification display label: in the form initialization assignment list object
# Tag lookup
def get_tag_list():
    return .values_list("name", "name")
 
# Form class definitions
class bookForm():
    tags = (label='Tags', widget=)
 
    def __init__(self, *args, **kwargs):
        super(cameraForm, self).__init__(*args, **kwargs)
        
        # Ensure an up-to-date list of tags for each initialization
        ['tags'].choices = get_tag_list()
        
        # Since it will be stored as a list string in the database, it needs to be converted back to a list object during assignment in order to recognize the original value when modifying the form.
        ['tags'] = eval(['tags'])    
 
    class Meta:
        model = book
        exclude = []
 
# book extension
class bookAdmin():
    search_fields = 'name', 'tags')
    list_display = ( 'name', 'tags')
    form = bookForm
 
# Register in admin
(book, bookAdmin)

Disposal results

Write to database format

Storing strings as a list in a database

django form styles

Above is the django admin to achieve dynamic multiple choice box form sample code in detail , more about django admin multiple choice box form information please pay attention to my other related articles !