Django: How to build a custom form widget?

后端 未结 5 1603
一生所求
一生所求 2020-11-28 23:23

I am having a difficult time finding documentation on how to write a custom widget.

My questions are:

  • If I build a custom widget, can it be used equiva
5条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-29 00:06

    Django <1.11

    Additionally to the other answers, this is a small code sample of a custom widget:

    widgets.py:

    from django.forms.widgets import Widget
    from django.template import loader
    from django.utils.safestring import mark_safe
    
    
    class MyWidget(Widget):
        template_name = 'myapp/my_widget.html'
    
        def get_context(self, name, value, attrs=None):
            return {'widget': {
                'name': name,
                'value': value,
            }}
    
        def render(self, name, value, attrs=None):
            context = self.get_context(name, value, attrs)
            template = loader.get_template(self.template_name).render(context)
            return mark_safe(template)
    

    my_widget.html:

    
    

    Django 1.11

    Widgets are now rendered using the form rendering API.

提交回复
热议问题