This article mainly introduces Django background custom form controls in Python. In fact, django has provided some available form controls for us, such as multiple selection boxes and single-choice buttons, if you are interested, start the business. This article mainly introduces Django background custom form controls in Python. In fact, django has provided some available form controls for us, such as multiple selection boxes and single-choice buttons, if you are interested, start the business.
In django, we canadmin.py
Add ModelAdmin
In this way, you can easily add, delete, modify, and query operations in the background. HoweverModel
The generated forms are not friendly. we hope to make various types of controls like front-end development, so we have to customize the forms in the background.
In fact, django has provided us with some available form controls, such as multi-choice boxes and single-choice buttons. the following uses single-choice buttons as an example:
# Forms. pyfrom django import formsfrom. models import MyModelclass MyForm (forms. modelForm): xxx = forms. choiceField (choices = [...], widget = forms. radioSelect () class Meta: model = MyModel fields = ['id', 'XXX'] # admin. pyfrom django. contrib import adminfrom. models import MyModelfrom. forms import MyFormclass MyAdmin (admin. modelAdmin): form = MyForm #... the admin code is omitted. site. register (MyModel, MyAdmin)
First customizeMyForm
, Add a control for the field,widget
Used to specify the control type,choices
Specify the optional list, and thenMyAdmin
You can specify the form as a custom form.
Many widgets have been provided in django, but these are far from satisfying our needs. Therefore, we need to customize them, the following uses an ACE plug-in (ACE is an independent JavaScript-based Web code editor) as an example to describe how to customize widgets:
# Coding: utf-8from django import formsfrom django.utils.html import format_htmlfrom django. forms. utils import flatattfrom django. utils. encoding import force_textfrom django. utils. safestring import mark_safeACE_RENDER = '''