A
A
awd102017-03-03 21:50:36
Django
awd10, 2017-03-03 21:50:36

How to make custom form widgets in django?

Interested in 3 questions:
1. How to connect and use your .html template in the widget?
2. How to make a custom template inside the widget (the minimum set of tags)?
3. How to properly store your widget in the application:

-myapp:
--forms:
---widget.py
---templates:
----mywidget.html

Is this a good option or do I need to do something else?
Thanks.
I will add a simple snippet, maybe it will come in handy for someone:
widgets.py
from django import forms
from django.forms.utils import flatatt
from django.utils.html import format_html


class Tags(forms.TextInput):
    input_type = 'text'
#переопределяем рендер
    def render(self, name=None, value=None, attrs=None):
        attrs = dict(self.attrs, **attrs) if attrs else self.attrs
        final_attrs = dict(attrs, type=self.input_type, name=name)
        return format_html('<input {} >', flatatt(final_attrs)) # flatatt позволяет пребразовать словарь в нормальные пары
# подключаем статику
    class Media:
        css = {
            'all': ('style.css',)
        }
        js = 'script.js'

and in forms, we just connect the widget:
test = forms.CharField(widget=Tags)
and if everything is completely bad and lazy, then you can use https://django-floppyforms.readthedocs.io/en/latest/

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
sim3x, 2017-03-04
@awd10

In the case of widget development, html and python interfere
And mywidget.html is not needed
https://github.com/yourlabs/django-autocomplete-li...
https://github.com/yourlabs/django-autocomplete-li...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question