How do you change the default widget for all Django date fields in a ModelForm?

前端 未结 6 1026
夕颜
夕颜 2020-11-30 18:48

Given a set of typical models:

# Application A
from django.db import models
class TypicalModelA(models.Model):
    the_date = models.DateField()

 # Applicat         


        
6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-30 19:15

    Well, making a custom model field just to change it's default form widget is not really the obvious place to start.

    You can make your own form widget and override the field in the form, specifying your own widget like in Soviut's answer.

    There's also a shorter way:

    class ArticleForm(ModelForm):
         pub_date = DateField(widget=MyDateWidget())
    
         class Meta:
             model = Article
    

    There is an example of how to write form widgets, it's somewhere in the forms package of Django. It's a datepicker with 3 dropdowns.

    What I usually do when I just want to add some JavaScript to a standard HTML input element is leave it the way it is and modify it by referencing it's id later with JavaScript. You can easily catch the naming convention for the ids of the input fields Django generates.

    You can also just provide the class for the widget when you override it in the form. Then catch them all with jQuery by the class name.

提交回复
热议问题