Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
409 views
in Technique[技术] by (71.8m points)

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

Given a set of typical models:

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

 # Application B
from django.db import models
class TypicalModelB(models.Model):
    another_date = models.DateField()

...

How might one change the default widget for all DateFields to a custom MyDateWidget?

I'm asking because I want my application to have a jQueryUI datepicker for inputting dates.

I've considered a custom field that extends django.db.models.DateField with my custom widget. Is this the best way to implement this sort of across-the-board change? Such a change will require specifically importing a special MyDateField into every model, which is labour intensive, prone to developer error (i.e. a few models.DateField's will get through), and in my mind seems like unnecessary duplication of effort. On the other hand, I don't like modifying what could be considered the canonical version of models.DateField.

Thoughts and input is appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can declare an attribute on your ModelForm class, called formfield_callback. This should be a function which takes a Django model Field instance as an argument, and returns a form Field instance to represent it in the form.

Then all you have to do is look to see if the model field passed in is an instance of DateField and, if so, return your custom field/widget. If not, the model field will have a method named formfield that you can call to return its default form field.

So, something like:

def make_custom_datefield(f):
    if isinstance(f, models.DateField):
        # return form field with your custom widget here...
    else:
        return f.formfield(**kwargs)

class SomeForm(forms.ModelForm)
    formfield_callback = make_custom_datefield

    class Meta:
        # normal modelform stuff here...

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...