Example of a Django background custom form control in Python

Source: Internet
Author: User
Tags myadmin
This article mainly introduces the Django background custom form control in Python, in fact Django has provided us with some available form controls, such as: Multi-box, radio button, etc., interested in opening to understand.

In Django we can add in admin.py ModelAdmin , so that it is easy to do in the background of the operation of the addition and deletion. However, the Model resulting form is not friendly, and we want to be able to make various types of controls like front-end development, which will have to be customized for the forms behind it.

In fact, Django has provided us with some form controls available, such as multi-marquee, radio button, and so on, with the radio button 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  # ... Omit several code admin.site.register (MyModel, MyAdmin)

Customize the first MyForm , add controls to the field, specify widget the type of control, specify an choices optional list, and then specify the form in MyAdmin the form as custom.

The

has provided many widgets (controls) in Django, but these are far from satisfying our needs, which requires us to customize, as an example of an ace plug-in, a Web-based code editor written by an independent JavaScript, to say how Custom Widget:

#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/ace.js" ></    Script><script> $ (function () {var textarea = $ (' textarea ');      var EDITP = $ (' <p> ', {position: ' absolute ', width:textarea.width (), Height:textarea.height (),    ' Class ': textarea.attr (' class ')}). InsertBefore (textarea);    Textarea.css (' Display ', ' none ');    var editor = Ace.edit (editp[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 be able to customize the code type and style at the time of the call:p Aram mode::p Aram theme::p Aram Attrs:: return: ' sup    ER (acewidget, self). __init__ (attrs) Self.mode = mode Self.theme = Theme def render (self, name, value, Attrs=none):    "Key method:p Aram Name::p Aram Value::p Aram Attrs:: Return: ' if value is None:value = ' ' Final_attrs = Self.build_attrs (attrs, name=name) output = [format_html (' <textarea{}>\r\n{}</textarea> ', F Latatt (Final_attrs), Force_text (value))] Current_ace_render = ace_render% (Self.mode, Self.theme) output.append (curr Ent_ace_render) return Mark_safe (' \ n '. Join (output))

The main thing is that the custom widget inherits from the Django widget, and then overrides the Render method, in which the new control is wrapped.

To forms.py introduce a custom control AceWidget into:

#coding: Utf-8from Django import formsfrom. Models import codefrom Widgets import Acewidgetclass codeform (forms. Modelform):  code = forms. Charfield (label= ' source code ', Widget=acewidget (attrs={' cols ': ' + ', ' Rows ': ' $ '}, mode= "Python", theme= "Monokai"))  Class Meta:    model = Code fields    = [' title ', ' Code ']

It is important to note that the mode="python", theme="monokai" corresponding files are used here mode-python.js and theme-monokai.js must be in the /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 = ' codes '  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)
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.