Django ModelForm with Admin Widgets

2019-05-11 22:39发布

I have created models and from the models, I created ModelForms. However, I noticed that the widgets generated from the ModelForm are not as same as the widgets when I am in Admin pages.

How can I:

  1. Get the same widget as the ones in admin pages. Those are awesome. The foreign key field comes with 'plus' icon that enables you to add new item being referenced to.

  2. Date time widget has 'Now' button that enables you to populate the field instantly with the current time.

  3. Is there any other cool plugin out there for the widgets? So far all I got is meh, just plain html widget that doesnt make sense even for field like Datetime (it generates normal plain input control).

1条回答
Ridiculous、
2楼-- · 2019-05-11 22:43

You should have a look to django/contrib/admin/widgets.py You will find here the admin site widgets. Then in you form, make something like:

from django.contrib.admin.widgets import AdminDateWidget

class MyForm(ModelForm):

    class Meta:
        widgets = {
            'date': AdminDateWidget(),
        }

Make sure that your template includes the required media files (css, js)

I also recommend to look at django-floppyforms which is a very nice lib if you want better widgets

查看更多
登录 后发表回答