Python: custom form control in Django background, pythondjango
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 = ''' <script src = "/static/js/jquery-1.11.2.min.js"> </script> <script src = "/static/js/ace. js "> </script> <script >$ (function () {var textarea =$ ('textta'); var editDiv =$ ('<div>', {position: 'abort', width: textarea. width (), height: textarea. height (), 'class': textarea. attr ('class ')}). insertBefore (textarea); textarea.css ('display', 'None'); var editor = ace. edit (editDiv [0]); editor. getSession (). setValue (textarea. val (); editor. getSession (). setMode ("ace/mode/% s"); editor. setTheme ("ace/theme/% s"); textarea. closest ('form '). submit (function () {textarea. val (editor. getSession (). getValue () ;};}); </script> ''' class AceWidget (forms. textarea): def _ init _ (self, mode = "", theme = "", attrs = None ): ''' In order to customize the code type and style when calling: param mode: param theme: param attrs: return: ''' super (AceWidget, self ). _ init _ (attrs) self. mode = mode self. theme = theme def render (self, name, value, attrs = None): ''' key method: param name: param value: param attrs: return: '''if value is None: value = ''' final_attrs = self. build_attrs (attrs, name = name) output = [format_html ('<textarea {}> \ r \ n {}</textarea>', flatatt (final_attrs ), force_text (value)] current_ace_render = ACE_RENDER % (self. mode, self. theme) output. append (current_ace_render) return mark_safe ('\ n '. join (output ))
The main difference is that custom widgets inherit from django widgets, and then rewrite the render method. In this method, new widgets are encapsulated.
Informs.py
Set Custom ControlsAceWidget
Introduction:
# Coding: utf-8from django import formsfrom. models import Codefrom widgets import AceWidgetclass CodeForm (forms. modelForm): code = forms. charField (label = 'source', widget = AceWidget (attrs = {'cols': '000000', 'rows ': '20'}, mode = "python ", theme = "monokai") class Meta: model = Code fields = ['title', 'code']
Note thatmode="python", theme="monokai"
Corresponding Filemode-python.js
Andtheme-monokai.js
Be sure/static/js/ace
Directory.
Appendix:
models.py:
# Coding: utf-8from django. db import modelsclass Code (models. model): title = models. charField ('title', max_length = 50, unique = True) code = models. textField ('source') class Meta: db_table = 'code' verbose_name = verbose_name_plural = 'code' def _ unicode _ (self): return self. title
admin.py:
from django.contrib import adminfrom .models import Codefrom .forms import CodeFormclass CodeAdmin(admin.ModelAdmin): form = CodeForm list_display = ['id', 'title']admin.site.register(Code, CodeAdmin)
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.