2

I'm making a user login form with a CustomUser model derived from AbstractUser, with one extra field: date_of_birth. I use CreateView to generate the form. All fields show up, the password field uses the password widget as expected (showing dots instead of characters), but the date field does not (plain character field with no formatting or calendar). What am I overlooking?

models.py:

from django.urls import reverse
from django.contrib.auth.models import AbstractUser

# Create your models here.
class CustomUser(AbstractUser):
    date_of_birth = models.DateField(verbose_name="Date of Birth", blank=True, null=True)

    def get_absolute_url(self):
        return reverse('index')
    def __str__(self):
        return self.username

forms.py:

from .models import CustomUser


class CustomUserForm(forms.ModelForm):
    class Meta:
        model = CustomUser
        fields = ["username", "password", "first_name", "last_name", "email", "date_of_birth"]
        widgets = {
            "password": forms.PasswordInput(),
            "date_of_birth": forms.DateInput()
        }

views.py:

from django.views.generic.edit import CreateView
from .models import CustomUser
from .forms import CustomUserForm

# Create your views here.
def index(request):
    return HttpResponse("Hello, world")


class CustomUserCreate(CreateView):
    model = CustomUser
    form_class = CustomUserForm
1
  • Which browser are you testing on? Check out this. Commented Nov 25, 2019 at 15:25

3 Answers 3

11

If you come here in 2020 and beyond, just overide the default type=text undelying input by using 'type':'date'

So something like the below would work. Tested on Mozilla Dev Edition 73.+

'date_of_birth': forms.DateInput(attrs={'class':'form-control', 'type':'date'}),
Sign up to request clarification or add additional context in comments.

1 Comment

You're right, works! Is described in the docs as well: docs.djangoproject.com/en/3.0/ref/forms/widgets/…
3

Django has no built-in fancy datepicker. DateField uses the DateInput widget which is just a text input.

Comments

1

Thanks voodoo-burger for pointing me in the right direction. I found a video with a very simple solution to use the HTML5 datepicker: https://www.youtube.com/watch?v=I2-JYxnSiB0.

It only requires to add the following to forms.py:

class DateInput(forms.DateInput):
    input_type = 'date'

and then use this as the widget (so replace forms.DateInput() with DateInput()).

1 Comment

Glad I could help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.