Question

In my model I have a Datefield. So I want to use a Datepicker. How to use the Django-Admin Datepicker?

I have found examples to do this in a Form, but I have only desined a model. Is it possible to define this widget in my Model?

Était-ce utile?

La solution

You can use get_form method to override widget attribute:

class MyCreateView(CreateView):
    def get_form(self, form_class):
        form = super(MyCreateView, self).get_form(form_class)
        form.fields['date_field'].widget.attrs.update({'class': 'datepicker'})
        return form

Autres conseils

I'll suggest you to create a modelform, in that form file import the admin datepicker widget

from django.contrib.admin.widgets import AdminDateWidget

and define the widgets for that field using attrs=AdminDateWidget

and in template put {{ form.media }} to get include that widget javascript and css files in html

Here is a full, modern solution based on the other answers:

from django.views.generic import CreateView
from django.contrib.admin.widgets import AdminDateWidget
from .models import MyModel

class MyModelCreateView(CreateView):
    template_name = 'form.html'
    model = MyModel
    fields = ['date_field', ...]

    def get_form(self, form_class=None):
        form = super(MyModelCreateView, self).get_form(form_class)
        form.fields['date_field'].widget = AdminDateWidget(attrs={'type': 'date'})
        return form
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top